<?php

/**
 * [Discuz!] (C)2001-2099 Comsenz Inc.
 * This is NOT a freeware, use is subject to license terms
 *
 * $Id: admincp_forums.php 23399 2011-07-13 10:12:39Z liulanbo $
 */

if (!defined('IN_DISCUZ') || !defined('IN_ADMINCP')){
	exit('Access Denied');
}

cpheader();

$operation = empty($operation) ? 'admin' : $operation;
$sid = getgpc('sid');

if ($operation == 'admin'){

	if (!submitcheck('editsubmit')){
		shownav('shop', 'shop_admin_category');
		showsubmenu('shop_admin_category');
		showtips('shop_admin_tips');

		require_once libfile('function/shoplist');
		$shops = str_replace("'", "\'", shopselect(false, 0, 0, 1));

		?>
<script type="text/javaScript">
var shopselect = '<?=$shops;?>';
var rowtypedata = [
	[[1, ''], [1,'<input type="text" class="txt" name="newcatorder[]" value="0" />', 'td25'], [5, '<div><input name="newcat[]" value="<?php
		cplang('forums_admin_add_category_name', null, true);
		?>" size="20" type="text" class="txt" /><a href="javascript:;" class="deleterow" onClick="deleterow(this)"><?php
		cplang('delete', null, true);
		?></a></div>']],
	[[1, ''], [1,'<input type="text" class="txt" name="neworder[{1}][]" value="0" />', 'td25'], [5, '<div class="board"><input name="newforum[{1}][]" value="<?php
		cplang('shop_admin_add_shop_name', null, true);
		?>" size="20" type="text" class="txt" /><a href="javascript:;" class="deleterow" onClick="deleterow(this)"><?php
		cplang('delete', null, true);
		?></a><select name="newinherited[{1}][]"><option value=""><?php
		cplang('forums_edit_newinherited', null, true);
		?></option>' + shopselect + '</select></div>']],
	[[1, ''], [1,'<input type="text" class="txt" name="neworder[{1}][]" value="0" />', 'td25'], [5, '<div class="childboard"><input name="newforum[{1}][]" value="<?php
		cplang('shop_admin_add_shop_name', null, true);
		?>" size="20" type="text" class="txt" /><a href="javascript:;" class="deleterow" onClick="deleterow(this)"><?php
		cplang('delete', null, true);
		?></a>&nbsp;<label><input name="inherited[{1}][]" type="checkbox" class="checkbox" value="1">&nbsp;<?php
		cplang('forums_edit_inherited', null, true);
		?></label></div>']],
];
</script>
<?php
		showformheader('shops');
		echo '<div style="height:30px;line-height:30px;"><a href="javascript:;" onclick="show_all()">' . cplang('show_all') . '</a> | <a href="javascript:;" onclick="hide_all()">' . cplang('hide_all') . '</a></div>';
		showtableheader('');
		showsubtitle(array(
				'',
				'display_order',
				'shop_admin_category',
				'',
				'forums_moderators',
				'<a href="javascript:;" onclick="if(getmultiids()) location.href=\'' . ADMINSCRIPT . '?action=shops&operation=edit&multi=\' + getmultiids();return false;">' . $lang['multiedit'] . '</a>'
		));

		$shopcount = DB::result_first("SELECT COUNT(*) FROM " . DB::table('shop_category') . " WHERE `status`<>3");

		$query = DB::query("SELECT s.sid, s.type, s.status, s.name, s.sup, s.hot, s.compare, s.displayorder, s.inheritedmod, ss.moderators, ss.password, ss.redirect
							FROM " . DB::table('shop_category') . " s
							LEFT JOIN " . DB::table('shop_shopfield') . " ss USING(sid)
							WHERE s.status<>'3'
							ORDER BY s.type<>'group', s.displayorder");

		$groups = $shops = $subs = $sids = $showed = array();
		while ($shop = DB::fetch($query)){
			if ($shop['type'] == 'group'){
				$groups[$shop['sid']] = $shop;
			}elseif ($shop['type'] == 'sub'){
				$subs[$shop['sup']][] = $shop;
			}else{
				$shops[$shop['sup']][] = $shop;
			}
			$sids[] = $shop['sid'];
		}

		foreach ($groups as $id=>$gforum){
			$toggle = $shopcount > 50 && count($shops[$id]) > 2;
			$showed[] = showforum($gforum, 'group', '', $toggle);
			if (!empty($shops[$id])){
				foreach ($shops[$id] as $shop){
					$showed[] = showforum($shop);
					$lastsid = 0;
					if (!empty($subs[$shop['sid']])){
						foreach ($subs[$shop['sid']] as $sub){
							$showed[] = showforum($sub, 'sub');
							$lastsid = $sub['sid'];
						}
					}
					showforum($shop, $lastsid, 'lastchildboard');
				}
			}
			showforum($gforum, '', 'lastboard');
		}

		if (count($sids) != count($showed)){
			foreach ($sids as $sid){
				if (!in_array($sid, $showed)){
					DB::update('shop_category', array(
							'sup'=>'0',
							'type'=>'shop'
					), "sid='$sid'");
				}
			}
		}

		showforum($gforum, '', 'last');

		showsubmit('editsubmit');
		showtablefooter();
		showformfooter();

	}else{
		$usergroups = array();
		$query = DB::query("SELECT groupid, type, creditshigher, creditslower
							FROM " . DB::table('common_usergroup') . "");
		while ($group = DB::fetch($query)){
			$usergroups[$group['groupid']] = $group;
		}

		if (is_array($_G['gp_order'])){
			foreach ($_G['gp_order'] as $sid=>$value){
				DB::update('shop_category', array(
						'name'=>$_G['gp_name'][$sid],
						'displayorder'=>$_G['gp_order'][$sid]
				), "sid='$sid'");
			}
		}

		if (is_array($_G['gp_newcat'])){
			foreach ($_G['gp_newcat'] as $key=>$shopname){
				if (empty($shopname)){
					continue;
				}
				$sid = DB::insert('shop_category', array(
						'type'=>'group',
						'name'=>$shopname,
						'status'=>1,
						'displayorder'=>$_G['gp_newcatorder'][$key]
				), 1);
				DB::insert('shop_shopfield', array(
						'sid'=>$sid
				));
			}
		}

		$table_shop_columns = array(
				'sup',
				'type',
				'name',
				'status',
				'hot',
				'displayorder',
				'styleid',
				'allowsmilies',
				'allowhtml',
				'allowbbcode',
				'allowimgcode',
				'allowanonymous',
				'allowpostspecial',
				'alloweditrules',
				'alloweditpost',
				'modnewposts',
				'recyclebin',
				'jammer',
				'shopcolumns',
				'threadcaches',
				'disablewatermark',
				'disablethumb',
				'autoclose',
				'simple',
				'allowside',
				'allowfeed'
		);
		$table_shopfield_columns = array(
				'sid',
				'attachextensions',
				'threadtypes',
				'viewperm',
				'postperm',
				'replyperm',
				'getattachperm',
				'postattachperm',
				'postimageperm'
		);

		if (is_array($_G['gp_newforum'])){

			foreach ($_G['gp_newforum'] as $sup=>$shops){

				$supforum = get_shop_by_sid($sup);
				if (empty($supforum))
					continue;

				if ($supforum['sup']){
					$groupforum = get_shop_by_sid($supforum['sup']);
				}else{
					$groupforum = $supforum;
				}

				foreach ($shops as $key=>$shopname){

					if (empty($shopname))
						continue;

					$shop = $shopfields = array();
					$inheritedid = !empty($_G['gp_inherited'][$sup]) ? $sup : (!empty($_G['gp_newinherited'][$sup][$key]) ? $_G['gp_newinherited'][$sup][$key] : '');

					if (!empty($inheritedid)){

						$shop = get_shop_by_sid($inheritedid);
						$shopfield = get_shop_by_sid($inheritedid, null, 'shopfield');

						foreach ($table_shop_columns as $field){
							$shopfields[$field] = $shop[$field];
						}

						foreach ($table_shopfield_columns as $field){
							$shopfields[$field] = $shopfield[$field];
						}

					}else{
						$shopfields['allowsmilies'] = $shopfields['allowbbcode'] = $shopfields['allowimgcode'] = 1;
						$shopfields['allowpostspecial'] = 1;
						$shopfields['allowside'] = 0;
						$shopfields['allowfeed'] = 0;
						$shopfields['recyclebin'] = 1;
					}

					$shopfields['sup'] = $sup ? $sup : 0;
					$shopfields['type'] = $supforum['type'] == 'shop' ? 'sub' : 'shop';
					$shopfields['styleid'] = $groupforum['styleid'];
					$shopfields['name'] = $shopname;
					$shopfields['status'] = 1;
					$shopfields['displayorder'] = $_G['gp_neworder'][$sup][$key];

					$data = array();
					foreach ($table_shop_columns as $field){
						if (isset($shopfields[$field])){
							$data[$field] = $shopfields[$field];
						}
					}

					$shopfields['sid'] = $sid = DB::insert('shop_category', $data, 1);

					$data = array();
					$shopfields['threadtypes'] = copy_threadclasses($shopfields['threadtypes'], $sid);
					foreach ($table_shopfield_columns as $field){
						if (isset($shopfields[$field])){
							$data[$field] = $shopfields[$field];
						}
					}

					DB::insert('shop_shopfield', $data);

					$query = DB::query("SELECT uid, inherited FROM " . DB::table('shop_moderator') . " WHERE sid='$sup'");
					while ($mod = DB::fetch($query)){
						if ($mod['inherited'] || $supforum['inheritedmod']){
							DB::insert('shop_moderator', array(
									'uid'=>$mod['uid'],
									'sid'=>$sid,
									'inherited'=>1
							), 0, 1);
						}
					}
				}
			}
		}

		updatecache('shops');

		cpmsg('shop_update_succeed', 'action=shops', 'succeed');
	}

}elseif ($operation == 'moderators' && $sid){

	if (!submitcheck('modsubmit')){

		$shop = DB::fetch_first("SELECT * FROM " . DB::table('shop_category') . " WHERE sid='$sid'");
		shownav('shop', 'forums_moderators_edit');
		showsubmenu(cplang('forums_moderators_edit') . ' - ' . $shop['name']);
		showtips('forums_moderators_tips');
		showformheader("shops&operation=moderators&sid=$sid&");
		showtableheader('', 'fixpadding');
		showsubtitle(array(
				'',
				'display_order',
				'username',
				'usergroups',
				'forums_moderators_inherited'
		));

		$query = DB::query("SELECT a.admingid, u.radminid, u.grouptitle FROM " . DB::table('common_admingroup') . " a
							INNER JOIN " . DB::table('common_usergroup') . " u ON u.groupid=a.admingid
							WHERE u.radminid>'0'
							ORDER BY u.type, a.admingid");
		$modgroups = array();
		$groupselect = '<select name="newgroup">';
		while ($modgroup = DB::fetch($query)){
			if ($modgroup['radminid'] == 3){
				$groupselect .= '<option value="' . $modgroup['admingid'] . '">' . $modgroup['grouptitle'] . '</option>';
			}
			$modgroups[$modgroup['admingid']] = $modgroup['grouptitle'];
		}
		$groupselect .= '</select>';

		$query = DB::query("SELECT m.username, m.groupid, mo.*
							FROM " . DB::table('common_member') . " m, " . DB::table('shop_moderator') . " mo
							WHERE mo.sid='$sid' AND m.uid=mo.uid
							ORDER BY mo.inherited, mo.displayorder");
		while ($mod = DB::fetch($query)){
			showtablerow('', array(
					'class="td25"',
					'class="td28"'
			), array(
					'<input type="checkbox" class="checkbox" name="delete[]" value="' . $mod[uid] . '"' . ($mod['inherited'] ? ' disabled' : '') . ' />',
					'<input type="text" class="txt" name="displayordernew[' . $mod[uid] . ']" value="' . $mod[displayorder] . '" size="2" />',
					"<a href=\"" . ADMINSCRIPT . "?mod=shop&action=members&operation=group&uid=$mod[uid]\" target=\"_blank\">$mod[username]</a>",
					$modgroups[$mod['groupid']],
					cplang($mod['inherited'] ? 'yes' : 'no')
			));
		}

		if ($shop['type'] == 'group' || $shop['type'] == 'sub'){
			$checked = $shop['type'] == 'group' ? 'checked' : '';
			$disabled = 'disabled';
		}else{
			$checked = $shop['inheritedmod'] ? 'checked' : '';
			$disabled = '';
		}

		showtablerow('', array(
				'class="td25"',
				'class="td28"'
		), array(
				cplang('add_new'),
				'<input type="text" class="txt" name="newdisplayorder" value="0" size="2" />',
				'<input type="text" class="txt" name="newmoderator" value="" size="20" />',
				$groupselect,
				''
		));

		showsubmit('modsubmit', 'submit', 'del', '<input class="checkbox" type="checkbox" name="inheritedmodnew" value="1" ' . $checked . ' ' . $disabled . ' id="inheritedmodnew" /><label for="inheritedmodnew">' . cplang('forums_moderators_inherit') . '</label>');
		showtablefooter();
		showformfooter();

	}else{
		$shop = DB::fetch_first("SELECT * FROM " . DB::table('shop_category') . " WHERE sid='$sid'");
		$inheritedmodnew = $_G['gp_inheritedmodnew'];
		if ($shop['type'] == 'group'){
			$inheritedmodnew = 1;
		}elseif ($shop['type'] == 'sub'){
			$inheritedmodnew = 0;
		}

		if (!empty($_G['gp_delete']) || $_G['gp_newmoderator'] || (bool)$shop['inheritedmod'] != (bool)$inheritedmodnew){

			$sidarray = $newmodarray = $origmodarray = array();

			if ($shop['type'] == 'group'){
				$query = DB::query("SELECT sid FROM " . DB::table('shop_category') . " WHERE type='shop' AND sup='$sid'");
				while ($sub = DB::fetch($query)){
					$sidarray[] = $sub['sid'];
				}
				$query = DB::query("SELECT sid FROM " . DB::table('shop_category') . " WHERE type='sub' AND sup IN ('" . implode('\',\'', $sidarray) . "')");
				while ($sub = DB::fetch($query)){
					$sidarray[] = $sub['sid'];
				}
			}elseif ($shop['type'] == 'shop'){
				$query = DB::query("SELECT sid FROM " . DB::table('shop_category') . " WHERE type='sub' AND sup='$sid'");
				while ($sub = DB::fetch($query)){
					$sidarray[] = $sub['sid'];
				}
			}

			if (is_array($_G['gp_delete'])){
				foreach ($_G['gp_delete'] as $uid){
					DB::query("DELETE FROM " . DB::table('shop_moderator') . "
								WHERE uid='$uid' AND ((sid='$sid' AND inherited='0') OR (sid IN (" . dimplode($sidarray) . ") AND inherited='1'))");
				}

				$excludeuids = 0;
				$deleteuids = '\'' . implode('\',\'', $_G['gp_delete']) . '\'';
				$query = DB::query("SELECT uid FROM " . DB::table('shop_moderator') . " WHERE uid IN ($deleteuids)");
				while ($mod = DB::fetch($query)){
					$excludeuids .= ',' . $mod['uid'];
				}

				$usergroups = array();
				$query = DB::query("SELECT groupid, type, radminid, creditshigher, creditslower FROM " . DB::table('common_usergroup') . "");
				while ($group = DB::fetch($query)){
					$usergroups[$group['groupid']] = $group;
				}

				$query = DB::query("SELECT uid, groupid, credits
									FROM " . DB::table('common_member') . "
									WHERE uid IN ($deleteuids) AND uid NOT IN ($excludeuids) AND adminid NOT IN (1,2)");
				while ($member = DB::fetch($query)){
					if ($usergroups[$member['groupid']]['type'] == 'special' && $usergroups[$member['groupid']]['radminid'] != 3){
						$adminidnew = -1;
						$groupidnew = $member['groupid'];
					}else{
						$adminidnew = 0;
						foreach ($usergroups as $group){
							if ($group['type'] == 'member' && $member['credits'] >= $group['creditshigher'] && $member['credits'] < $group['creditslower']){
								$groupidnew = $group['groupid'];
								break;
							}
						}
					}
					DB::update('common_member', array(
							'adminid'=>$adminidnew,
							'groupid'=>$groupidnew
					), "uid='$member[uid]'");
				}
			}

			if ($_G['gp_newmoderator']){
				$member = DB::fetch_first("SELECT uid
											FROM " . DB::table('common_member') . "
											WHERE username='$_G[gp_newmoderator]'");
				if (!$member){
					cpmsg_error('members_edit_nonexistence');
				}else{
					$newmodarray[] = $member['uid'];
					DB::update('common_member', array(
							'groupid'=>$_G['gp_newgroup']
					), "uid='$member[uid]' AND adminid NOT IN (1,2,3,4,5,6,7,8,-1)");
					DB::update('common_member', array(
							'adminid'=>'3'
					), "uid='$member[uid]' AND adminid NOT IN (1,2)");
					DB::insert('shop_moderator', array(
							'uid'=>$member['uid'],
							'sid'=>$sid,
							'displayorder'=>$_G['gp_newdisplayorder'],
							'inherited'=>'0'
					), false, true);
				}
			}

			if ((bool)$shop['inheritedmod'] != (bool)$inheritedmodnew){
				$query = DB::query("SELECT uid FROM " . DB::table('shop_moderator') . " WHERE sid='$sid' AND inherited='0'");
				while ($mod = DB::fetch($query)){
					$origmodarray[] = $mod['uid'];
					if (!$shop['inheritedmod'] && $inheritedmodnew){
						$newmodarray[] = $mod['uid'];
					}
				}
				if ($shop['inheritedmod'] && !$inheritedmodnew){
					DB::query("DELETE FROM " . DB::table('shop_moderator') . " WHERE uid IN ('" . implode('\',\'', $origmodarray) . "') AND sid IN ('" . implode('\',\'', $sidarray) . "') AND inherited='1'");
				}
			}

			foreach ($newmodarray as $uid){
				DB::insert('shop_moderator', array(
						'uid'=>$uid,
						'sid'=>$sid,
						'displayorder'=>$_G['gp_newdisplayorder'],
						'inherited'=>'0'
				), false, true);

				if ($inheritedmodnew){
					foreach ($sidarray as $isid){
						DB::insert('shop_moderator', array(
								'uid'=>$uid,
								'sid'=>$isid,
								'inherited'=>'1'
						), false, true);
					}
				}
			}

			if ($shop['type'] == 'group'){
				$inheritedmodnew = 1;
			}elseif ($shop['type'] == 'sub'){
				$inheritedmodnew = 0;
			}
			DB::update('shop_category', array(
					'inheritedmod'=>$inheritedmodnew
			), "sid='$sid'");
		}

		if (is_array($_G['gp_displayordernew'])){
			foreach ($_G['gp_displayordernew'] as $uid=>$order){
				DB::update('shop_moderator', array(
						'displayorder'=>$order
				), "sid='$sid' AND uid='$uid'");
			}
		}

		$sidarray[] = $sid;
		foreach ($sidarray as $sid){
			$moderators = $tab = '';
			$query = DB::query("SELECT m.username FROM " . DB::table('common_member') . " m, " . DB::table('shop_moderator') . " mo WHERE mo.sid='$sid' AND mo.inherited='0' AND m.uid=mo.uid ORDER BY mo.displayorder");
			while ($mod = DB::fetch($query)){
				$moderators .= $tab . addslashes($mod['username']);
				$tab = "\t";
			}
			DB::update('shop_shopfield', array(
					'moderators'=>$moderators
			), "sid='$sid'");
		}
		cpmsg('forums_moderators_update_succeed', "mod=shop&action=shops&operation=moderators&sid=$sid", 'succeed');

	}

}elseif ($operation == 'merge'){
	// Action code here
}elseif ($operation == 'edit'){

	require_once libfile('function/shoplist');
	require_once libfile('function/domain');
	$highlight = getgpc('highlight');
	$anchor = getgpc('anchor');

	list($pluginsetting, $pluginvalue) = get_pluginsetting('shops');

	$multiset = 0;
	if (empty($_G['gp_multi'])){
		$sids = $sid;
	}else{
		$multiset = 1;
		if (is_array($_G['gp_multi'])){
			$sids = dimplode($_G['gp_multi']);
		}else{
			$_G['gp_multi'] = explode(',', $_G['gp_multi']);
			array_walk($_G['gp_multi'], 'intval');
			$sids = dimplode($_G['gp_multi']);
		}
	}
	if (count($_G['gp_multi']) == 1){
		$sids = $_G['gp_multi'][0];
		$multiset = 0;
	}
	if (empty($sids)){
		cpmsg('shop_edit_nonexistence', 'action=shops&operation=edit' . (!empty($highlight) ? "&highlight=$highlight" : '') . (!empty($anchor) ? "&anchor=$anchor" : ''), 'form', array(), '<select name="sid">' . shopselect(FALSE, 0, 0, TRUE) . '</select>');
	}
	$mshop = array();
	$perms = array(
			'viewperm',
			'postperm',
			'replyperm',
			'getattachperm',
			'postattachperm',
			'postimageperm'
	);

	$query = DB::query("SELECT *, s.sid AS sid
						FROM " . DB::table('shop_category') . " s
						LEFT JOIN " . DB::table('shop_shopfield') . " ss USING (sid)
						WHERE s.sid IN ($sids)");

	if (!DB::num_rows($query)){
		cpmsg('shop_nonexistence', '', 'error');
	}else{
		while ($shop = DB::fetch($query)){
			if (isset($pluginvalue[$shop['sid']])){
				$shop['plugin'] = $pluginvalue[$shop['sid']];
			}
			$mshop[] = $shop;
		}
	}

	$dactionarray = array();
	$allowthreadtypes = !in_array('threadtypes', $dactionarray);

	$query = DB::query("SELECT svalue FROM " . DB::table('common_setting') . " WHERE skey='forumkeys'");
	$shopkeys = @unserialize(DB::result($query, 0));

	$rules = array();
	$query = DB::query("SELECT * FROM " . DB::table('common_credit_rule') . " WHERE action IN('reply', 'post', 'digest', 'postattach', 'getattach')");
	while ($value = DB::fetch($query)){
		$rules[$value['rid']] = $value;
	}

	if (!submitcheck('detailsubmit')){
		$anchor = in_array($_G['gp_anchor'], array(
				'basic',
				'extend',
				'posts',
				'credits',
				'threadtypes',
				'threadsorts',
				'perm',
				'plugin'
		)) ? $_G['gp_anchor'] : 'basic';
		shownav('shop', 'forums_edit');

		loadcache('shops');
		$shopselect = '';
		$sgid = 0;
		foreach ($_G['cache']['shops'] as $shops){
			$checked = $sid == $shops['sid'] || in_array($shops['sid'], $_G['gp_multi']);
			if ($shops['type'] == 'group'){
				$sgid = $shops['sid'];
				$shopselect .= '</div><em class="cl">' . '<span class="right"><input name="checkall_' . $shops['sid'] . '" onclick="checkAll(\'value\', this.form, ' . $shops['sid'] . ', \'checkall_' . $shops['sid'] . '\')" type="checkbox" class="vmiddle checkbox" /></span>' . '<span class="pointer" onclick="sdisplay(\'g_' . $shops['sid'] . '\', this)"><img src="static/image/admincp/desc.gif" class="vmiddle" /></span> <span class="pointer" onclick="location.href=\'' . ADMINSCRIPT . '?action=shops&operation=edit&switch=yes&sid=' . $shops['sid'] . '\'">' . $shops['name'] . '</span></em><div id="g_' . $shops['sid'] . '" style="display:">';
			}elseif ($shops['type'] == 'shop'){
				$shopselect .= '<input class="left checkbox ck" chkvalue="' . $sgid . '" name="multi[]" value="' . $shops['sid'] . '" type="checkbox" ' . ($checked ? 'checked="checked" ' : '') . '/><a class="f' . ($checked ? ' current"' : '') . '" href="###" onclick="location.href=\'' . ADMINSCRIPT . '?action=shops&operation=edit&switch=yes&sid=' . $shops['sid'] . ($mshop[0]['type'] != 'group' ? '&anchor=\'+currentAnchor' : '\'') . '+\'&scrolltop=\'+scrollTopBody()">' . $shops['name'] . '</a>';
			}elseif ($shops['type'] == 'sub'){
				$shopselect .= '<input class="left checkbox ck" chkvalue="' . $sgid . '" name="multi[]" value="' . $shops['sid'] . '" type="checkbox" ' . ($checked ? 'checked="checked" ' : '') . '/><a class="s' . ($checked ? ' current"' : '') . '" href="###" onclick="location.href=\'' . ADMINSCRIPT . '?action=shops&operation=edit&switch=yes&sid=' . $shops['sid'] . ($mshop[0]['type'] != 'group' ? '&anchor=\'+currentAnchor' : '\'') . '+\'&scrolltop=\'+scrollTopBody()">' . $shops['name'] . '</a>';
			}
		}
		$shopselect = '<span id="fselect" class="right popupmenu_dropmenu" onmouseover="showMenu({\'ctrlid\':this.id,\'pos\':\'34\'});$(\'fselect_menu\').style.top=(parseInt($(\'fselect_menu\').style.top)-scrollTopBody())+\'px\';$(\'fselect_menu\').style.left=(parseInt($(\'fselect_menu\').style.left)-document.documentElement.scrollLeft-20)+\'px\'">' . cplang('forums_edit_switch') . '<em>&nbsp;&nbsp;</em></span>' . '<div id="fselect_menu" class="popupmenu_popup" style="display:none"><div class="fsel"><div>' . $shopselect . '</div></div><div class="cl"><input type="button" class="btn right" onclick="$(\'menuform\').submit()" value="' . cplang('forums_multiedit') . '" /></div></div>';

		showformheader('', '', 'menuform', 'get');
		showhiddenfields(array(
				'action'=>'shops',
				'operation'=>'edit'
		));
		if (count($mshop) == 1 && $mshop[0]['type'] == 'group'){
			showsubmenu(cplang('forums_cat_detail') . (count($mshop) == 1 ? ' - ' . $mshop[0]['name'] . '(gid:' . $mshop[0]['sid'] . ')' : ''), array(), $shopselect);
		}else{
			if ($multiset && !in_array($anchor, array(
					'basic',
					'extend',
					'posts',
					'perm',
					'plugin'
			))){
				$anchor = 'basic';
			}
			showsubmenuanchors(cplang('forums_edit') . (count($mshop) == 1 ? ' - ' . $mshop[0]['name'] . '(sid:' . $mshop[0]['sid'] . ')' : ''), array(
					array(
							'forums_edit_basic',
							'basic',
							$anchor == 'basic'
					),
					array(
							'forums_edit_extend',
							'extend',
							$anchor == 'extend'
					),
					array(
							'forums_edit_posts',
							'posts',
							$anchor == 'posts'
					),
					array(
							'forums_edit_perm',
							'perm',
							$anchor == 'perm'
					),
					!$multiset ? array(
							'forums_edit_credits',
							'credits',
							$anchor == 'credits'
					) : array(),
					!$multiset ? array(
							array(
									'menu'=>'usergroups_edit_other',
									'submenu'=>array(
											array(
													'forums_edit_threadtypes',
													'threadtypes',
													$anchor == 'threadtypes'
											),
											array(
													'forums_edit_threadsorts',
													'threadsorts',
													$anchor == 'threadsorts'
											),
											!$pluginsetting ? array() : array(
													'forums_edit_plugin',
													'plugin',
													$anchor == 'plugin'
											)
									)
							)
					) : array(),
					$multiset && $pluginsetting ? array(
							'forums_edit_plugin',
							'plugin',
							$anchor == 'plugin'
					) : array()
			), $shopselect);
		}
		showformfooter();

		$groups = array();
		$query = DB::query("SELECT type, groupid, grouptitle, radminid FROM " . DB::table('common_usergroup') . " ORDER BY (creditshigher<>'0' || creditslower<>'0'), creditslower, groupid");
		while ($group = DB::fetch($query)){
			$group['type'] = $group['type'] == 'special' && $group['radminid'] ? 'specialadmin' : $group['type'];
			$groups[$group['type']][] = $group;
		}

//		$styleselect = "<select name=\"styleidnew\"><option value=\"0\">$lang[use_default]</option>";
//		$query = DB::query("SELECT styleid, name FROM " . DB::table('common_style'));
//		while ($style = DB::fetch($query)){
//			$styleselect .= "<option value=\"$style[styleid]\" " . ($style['styleid'] == $mshop[0]['styleid'] ? 'selected="selected"' : NULL) . ">$style[name]</option>\n";
//		}
//		$styleselect .= '</select>';

		if (!$multiset){
			showtips('forums_edit_tips');
		}else{
			showtips('setting_multi_tips');
		}
		showformheader("shops&operation=edit&sid=$sid&", 'enctype');
		showhiddenfields(array(
				'type'=>$mshop[0]['type']
		));

		if (count($mshop) == 1 && $mshop[0]['type'] == 'group'){
			$mshop[0]['extra'] = unserialize($mshop[0]['extra']);
			showtableheader();
			showsetting('forums_edit_basic_cat_name', 'namenew', $mshop[0]['name'], 'text');
//			showsetting('forums_edit_basic_cat_name_color', 'extranew[namecolor]', $mshop[0]['extra']['namecolor'], 'color');
//			showsetting('forums_edit_basic_cat_style', '', '', $styleselect);
//			showsetting('forums_edit_extend_shop_horizontal', 'forumcolumnsnew', $mshop[0]['shopcolumns'], 'text');
//			showsetting('forums_edit_extend_cat_sub_horizontal', 'catforumcolumnsnew', $mshop[0]['catshopcolumns'], 'text');
//			if (!empty($_G['setting']['domain']['root']['shops'])){
//				showsetting('forums_edit_extend_domain', '', '', 'http://<input type="text" name="domainnew" class="txt" value="' . $mshop[0]['domain'] . '" style="width:100px; margin-right:0px;" >.' . $_G['setting']['domain']['root']['shops']);
//			}else{
//				showsetting('forums_edit_extend_domain', 'domainnew', '', 'text', 'disabled');
//			}
			showsetting('shop_cat_display', 'statusnew', $mshop[0]['status'], 'radio');
			showsetting('shop_category_hot', 'cathot', $mshop[0]['hot'], 'radio');
			showsetting('shop_compare_product', 'compare', $mshop[0]['compare'], 'radio');

			showtablefooter();
			showtips('setting_seo_shop_tips', 'seo_tips', true, 'setseotips');
			showtableheader();
			showsetting('forums_edit_basic_seotitle', 'seotitlenew', htmlspecialchars($mshop[0]['seotitle']), 'text');
			showsetting('forums_edit_basic_keyword', 'keywordsnew', htmlspecialchars($mshop[0]['keywords']), 'text');
			showsetting('forums_edit_basic_seodescription', 'seodescriptionnew', htmlspecialchars($mshop[0]['seodescription']), 'textarea');
			showsubmit('detailsubmit');
			showtablefooter();

		}else{

			require_once libfile('function/editor');

			if ($multiset){
				$_G['showsetting_multi'] = 0;
				$_G['showsetting_multicount'] = count($mshop);
				foreach ($mshop as $shop){
					$_G['showtableheader_multi'][] = '<a href="javascript:;" onclick="location.href=\'' . ADMINSCRIPT . '?action=shops&operation=edit&sid=' . $shop['sid'] . '&anchor=\'+$(\'cpform\').anchor.value;return false">' . $shop['name'] . '(sid:' . $shop['sid'] . ')</a>';
				}
			}
			$msids = array();
			foreach ($mshop as $shop){
				$sid = $shop['sid'];
				$msids[] = $sid;
				if (!$multiset){
					$supselect = "<select name=\"supnew\">\n";
					$query = DB::query("SELECT sid, type, name, sup
										FROM " . DB::table('shop_category') . "
										WHERE sid<>'$sid' AND type<>'sub' AND status<>'3'
										ORDER BY displayorder");
					while ($sup = DB::fetch($query)){
						$sups[] = $sup;
					}
					if (is_array($sups)){
						foreach ($sups as $shop1){
							if ($shop1['type'] == 'group'){
								$selected = $shop1['sid'] == $shop['sup'] ? "selected=\"selected\"" : NULL;
								$supselect .= "<option value=\"$shop1[sid]\" $selected>$shop1[name]</option>\n";
								foreach ($sups as $shop2){
									if ($shop2['type'] == 'shop' && $shop2['sup'] == $shop1['sid']){
										$selected = $shop2['sid'] == $shop['sup'] ? "selected=\"selected\"" : NULL;
										$supselect .= "<option value=\"$shop2[sid]\" $selected>&nbsp; &gt; $shop2[name]</option>\n";
									}
								}
							}
						}
						foreach ($sups as $shop0){
							if ($shop0['type'] == 'shop' && $shop0['sup'] == 0){
								$selected = $shop0['sid'] == $shop['sup'] ? "selected=\"selected\"" : NULL;
								$supselect .= "<option value=\"$shop0[sid]\" $selected>$shop0[name]</option>\n";
							}
						}
					}
					$supselect .= '</select>';

					if ($shop['threadtypes']){
						$shop['threadtypes'] = unserialize($shop['threadtypes']);
						$shop['threadtypes']['status'] = 1;
					}else{
						$shop['threadtypes'] = array(
								'status'=>0,
								'required'=>0,
								'listable'=>0,
								'prefix'=>0,
								'options'=>array()
						);
					}

					if ($shop['threadsorts']){
						$shop['threadsorts'] = unserialize($shop['threadsorts']);
						$shop['threadsorts']['status'] = 1;
					}else{
						$shop['threadsorts'] = array(
								'status'=>0,
								'required'=>0,
								'listable'=>0,
								'prefix'=>0,
								'options'=>array()
						);
					}

					$typeselect = $sortselect = '';

					$query = DB::query("SELECT * FROM " . DB::table('shop_threadtype') . " ORDER BY displayorder");
					$typeselect = getthreadclasses_html($sid);
					while ($type = DB::fetch($query)){
						$typeselected = array();
						$enablechecked = '';

						$keysort = $type['special'] ? 'threadsorts' : 'threadtypes';
						if (isset($shop[$keysort]['types'][$type['typeid']])){
							$enablechecked = ' checked="checked"';
						}

						$showtype = TRUE;

						loadcache('threadsort_option_' . $type['typeid']);
						if ($type['special'] && !$_G['cache']['threadsort_option_' . $type['typeid']]){
							$showtype = FALSE;
						}
						if ($type['special']){
							$typeselected[3] = $shop['threadsorts']['show'][$type['typeid']] ? ' checked="checked"' : '';
							$sortselect .= $showtype ? showtablerow('', array(
									'class="td25"'
							), array(
									'<input type="checkbox" name="threadsortsnew[options][enable][' . $type['typeid'] . ']" value="1" class="checkbox"' . $enablechecked . ' />',
									$type['name'],
									$type['description'],
									"<input class=\"checkbox\" type=\"checkbox\" name=\"threadsortsnew[options][show][{$type[typeid]}]\" value=\"3\" $typeselected[3] />",
									"<input class=\"radio\" type=\"radio\" name=\"threadsortsnew[defaultshow]\" value=\"$type[typeid]\" " . ($shop['threadsorts']['defaultshow'] == $type['typeid'] ? 'checked' : '') . " />"
							), TRUE) : '';
						}
					}
					$shop['creditspolicy'] = $shop['creditspolicy'] ? unserialize($shop['creditspolicy']) : array();
				}

				if ($shop['autoclose']){
					$shop['autoclosetime'] = abs($shop['autoclose']);
					$shop['autoclose'] = $shop['autoclose'] / abs($shop['autoclose']);
				}

				if ($shop['threadplugin']){
					$shop['threadplugin'] = unserialize($shop['threadplugin']);
				}

				$simplebin = sprintf('%08b', $shop['simple']);
				$shop['defaultorderfield'] = bindec(substr($simplebin, 0, 2));
				$shop['defaultorder'] = ($shop['simple'] & 32) ? 1 : 0;
				$shop['subforumsindex'] = bindec(substr($simplebin, 3, 2));
				$shop['subforumsindex'] = $shop['subforumsindex'] == 0 ? -1 : ($shop['subforumsindex'] == 2 ? 0 : 1);
				$shop['simple'] = $shop['simple'] & 1;
				$shop['modrecommend'] = $shop['modrecommend'] ? unserialize($shop['modrecommend']) : '';
				$shop['formulaperm'] = unserialize($shop['formulaperm']);
				$shop['medal'] = $shop['formulaperm']['medal'];
				$shop['formulapermmessage'] = stripslashes($shop['formulaperm']['message']);
				$shop['formulapermusers'] = $shop['formulaperm']['users'];
				$shop['formulaperm'] = $shop['formulaperm'][0];
				$shop['extra'] = unserialize($shop['extra']);
				$shop['threadsorts']['default'] = $shop['threadsorts']['defaultshow'] ? 1 : 0;

				$_G['multisetting'] = $multiset ? 1 : 0;
				showtagheader('div', 'basic', $anchor == 'basic');
				showtableheader('forums_edit_basic', 'nobottom');
				showsetting('forums_edit_basic_name', 'namenew', $shop['name'], 'text');
//				showsetting('forums_edit_base_name_color', 'extranew[namecolor]', $shop['extra']['namecolor'], 'color');
				if (!$multiset){
					if ($shop['icon']){
						$valueparse = parse_url($shop['icon']);
						if (isset($valueparse['host'])){
							$shopicon = $shop['icon'];
						}else{
							$shopicon = $_G['setting']['attachurl'] . 'common/' . $shop['icon'] . '?' . random(6);
						}
						$shopiconhtml = '<label><input type="checkbox" class="checkbox" name="deleteicon" value="yes" /> ' . $lang['delete'] . '</label><br /><img src="' . $shopicon . '" /><br />';
					}
					showsetting('forums_edit_basic_icon', 'iconnew', $shop['icon'], 'filetext', '', 0, $shopiconhtml);
					showsetting('forums_edit_basic_icon_width', 'extranew[iconwidth]', $shop['extra']['iconwidth'], 'text');
					if ($shop['banner']){
						$valueparse = parse_url($shop['banner']);
						if (isset($valueparse['host'])){
							$shopbanner = $shop['banner'];
						}else{
							$shopbanner = $_G['setting']['attachurl'] . 'common/' . $shop['banner'] . '?' . random(6);
						}
						$shopbannerhtml = '<label><input type="checkbox" class="checkbox" name="deletebanner" value="yes" /> ' . $lang['delete'] . '</label><br /><img src="' . $shopbanner . '" /><br />';
					}
					showsetting('forums_edit_basic_banner', 'bannernew', $shop['banner'], 'filetext', '', 0, $shopbannerhtml);
				}
				showsetting('shop_edit_basic_display', 'statusnew', $shop['status'], 'radio');
				showsetting('shop_category_hot', 'cathot', $shop['hot'], 'radio');
				showsetting('shop_compare_product', 'compare', $mshop[0]['compare'], 'radio');

				if (!$multiset){
					showsetting('forums_edit_basic_up', '', '', $supselect);
				}
				showsetting('forums_edit_basic_redirect', 'redirectnew', $shop['redirect'], 'text');
				showmultititle();
				showsetting('forums_edit_basic_description', 'descriptionnew', str_replace('&amp;', '&', html2bbcode($shop['description'])), 'textarea');
				showsetting('forums_edit_basic_rules', 'rulesnew', str_replace('&amp;', '&', html2bbcode($shop['rules'])), 'textarea');
				showsetting('forums_edit_basic_keys', 'keysnew', $shopkeys[$sid], 'text');
				if (!empty($_G['setting']['domain']['root']['shops'])){
					$iname = $multiset ? "multinew[{$_G[showsetting_multi]}][domainnew]" : 'domainnew';
					showsetting('forums_edit_extend_domain', '', '', 'http://<input type="text" name="' . $iname . '" class="txt" value="' . $shop['domain'] . '" style="width:100px; margin-right:0px;" >.' . $_G['setting']['domain']['root']['shops']);
				}elseif (!$multiset){
					showsetting('forums_edit_extend_domain', 'domainnew', '', 'text', 'disabled');
				}
				showtablefooter();
				if (!$multiset){
					showtips('setting_seo_shop_tips', 'seo_tips', true, 'setseotips');
				}
				showtableheader();
				showsetting('forums_edit_basic_seotitle', 'seotitlenew', htmlspecialchars($shop['seotitle']), 'text');
				showsetting('forums_edit_basic_keyword', 'keywordsnew', htmlspecialchars($shop['keywords']), 'text');
				showsetting('forums_edit_basic_seodescription', 'seodescriptionnew', htmlspecialchars($shop['seodescription']), 'textarea');
				showtablefooter();
				showtagfooter('div');

				showtagheader('div', 'extend', $anchor == 'extend');
				showtableheader('forums_edit_extend', 'nobottom');
				showsetting('forums_edit_extend_style', '', '', $styleselect);
				if ($shop['type'] != 'sub'){
					showsetting('forums_edit_extend_sub_horizontal', 'forumcolumnsnew', $shop['shopcolumns'], 'text');
					showsetting('forums_edit_extend_subforumsindex', array(
							'subforumsindexnew',
							array(
									array(
											-1,
											cplang('default')
									),
									array(
											1,
											cplang('yes')
									),
									array(
											0,
											cplang('no')
									)
							),
							1
					), $shop['subforumsindex'], 'mradio');
					showsetting('forums_edit_extend_simple', 'simplenew', $shop['simple'], 'radio');
				}else{
					if ($_GET['multi']){
						showsetting('forums_edit_extend_sub_horizontal', '', '', cplang('forums_edit_sub_multi_tips'));
						showsetting('forums_edit_extend_subforumsindex', '', '', cplang('forums_edit_sub_multi_tips'));
						showsetting('forums_edit_extend_simple', '', '', cplang('forums_edit_sub_multi_tips'));
					}
				}
				showsetting('forums_edit_extend_widthauto', array(
						'widthautonew',
						array(
								array(
										0,
										cplang('default')
								),
								array(
										-1,
										cplang('forums_edit_extend_widthauto_-1')
								),
								array(
										1,
										cplang('forums_edit_extend_widthauto_1')
								)
						),
						1
				), $shop['widthauto'], 'mradio');
				showsetting('forums_edit_extend_picstyle', 'picstylenew', $shop['picstyle'], 'radio');
				showmultititle();
				showsetting('forums_edit_extend_allowside', 'allowsidenew', $shop['allowside'], 'radio');
				showsetting('forums_edit_extend_recommend_top', 'allowglobalsticknew', $shop['allowglobalstick'], 'radio');
				showsetting('forums_edit_extend_defaultorderfield', array(
						'defaultorderfieldnew',
						array(
								array(
										0,
										cplang('forums_edit_extend_order_lastpost')
								),
								array(
										1,
										cplang('forums_edit_extend_order_starttime')
								),
								array(
										2,
										cplang('forums_edit_extend_order_replies')
								),
								array(
										3,
										cplang('forums_edit_extend_order_views')
								)
						)
				), $shop['defaultorderfield'], 'mradio');
				showsetting('forums_edit_extend_defaultorder', array(
						'defaultordernew',
						array(
								array(
										0,
										cplang('forums_edit_extend_order_desc')
								),
								array(
										1,
										cplang('forums_edit_extend_order_asc')
								)
						)
				), $shop['defaultorder'], 'mradio');
				showsetting('forums_edit_extend_threadcache', 'threadcachesnew', $shop['threadcaches'], 'text');
				showsetting('forums_edit_extend_relatedgroup', 'relatedgroupnew', $shop['relatedgroup'], 'text');
				showsetting('forums_edit_extend_edit_rules', 'alloweditrulesnew', $shop['alloweditrules'], 'radio');
				showmultititle();
				showsetting('forums_edit_extend_recommend', 'modrecommendnew[open]', $shop['modrecommend']['open'], 'radio', '', 1);
				showsetting('forums_edit_extend_recommend_sort', array(
						'modrecommendnew[sort]',
						array(
								array(
										1,
										cplang('forums_edit_extend_recommend_sort_auto')
								),
								array(
										0,
										cplang('forums_edit_extend_recommend_sort_manual')
								),
								array(
										2,
										cplang('forums_edit_extend_recommend_sort_mix')
								)
						)
				), $shop['modrecommend']['sort'], 'mradio');
				showsetting('forums_edit_extend_recommend_orderby', array(
						'modrecommendnew[orderby]',
						array(
								array(
										0,
										cplang('forums_edit_extend_recommend_orderby_dateline')
								),
								array(
										1,
										cplang('forums_edit_extend_recommend_orderby_lastpost')
								),
								array(
										2,
										cplang('forums_edit_extend_recommend_orderby_views')
								),
								array(
										3,
										cplang('forums_edit_extend_recommend_orderby_replies')
								),
								array(
										4,
										cplang('forums_edit_extend_recommend_orderby_digest')
								),
								array(
										5,
										cplang('forums_edit_extend_recommend_orderby_recommend')
								),
								array(
										6,
										cplang('forums_edit_extend_recommend_orderby_heats')
								)
						)
				), $shop['modrecommend']['orderby'], 'mradio');
				showsetting('forums_edit_extend_recommend_num', 'modrecommendnew[num]', $shop['modrecommend']['num'], 'text');
				showsetting('forums_edit_extend_recommend_imagenum', 'modrecommendnew[imagenum]', $shop['modrecommend']['imagenum'], 'text');
				showsetting('forums_edit_extend_recommend_imagesize', array(
						'modrecommendnew[imagewidth]',
						'modrecommendnew[imageheight]'
				), array(
						intval($shop['modrecommend']['imagewidth']),
						intval($shop['modrecommend']['imageheight'])
				), 'multiply');
				showsetting('forums_edit_extend_recommend_maxlength', 'modrecommendnew[maxlength]', $shop['modrecommend']['maxlength'], 'text');
				showsetting('forums_edit_extend_recommend_cachelife', 'modrecommendnew[cachelife]', $shop['modrecommend']['cachelife'], 'text');
				showsetting('forums_edit_extend_recommend_dateline', 'modrecommendnew[dateline]', $shop['modrecommend']['dateline'], 'text');
				showtablefooter();
				showtagfooter('div');

				showtagheader('div', 'posts', $anchor == 'posts');
				showtableheader('forums_edit_posts', 'nobottom');
				showsetting('forums_edit_posts_modposts', array(
						'modnewpostsnew',
						array(
								array(
										0,
										cplang('none')
								),
								array(
										1,
										cplang('forums_edit_posts_modposts_threads')
								),
								array(
										2,
										cplang('forums_edit_posts_modposts_posts')
								)
						)
				), $shop['modnewposts'], 'mradio');
				showsetting('shop_edit_posts_alloweditpost', 'alloweditpostnew', $shop['alloweditpost'], 'radio');
				showsetting('forums_edit_posts_allowappend', 'allowappendnew', $shop['allowappend'], 'radio');
				showsetting('forums_edit_posts_recyclebin', 'recyclebinnew', $shop['recyclebin'], 'radio');
				showmultititle();
				showsetting('forums_edit_posts_html', 'allowhtmlnew', $shop['allowhtml'], 'radio');
				showsetting('forums_edit_posts_bbcode', 'allowbbcodenew', $shop['allowbbcode'], 'radio');
				showsetting('forums_edit_posts_imgcode', 'allowimgcodenew', $shop['allowimgcode'], 'radio');
				showsetting('forums_edit_posts_mediacode', 'allowmediacodenew', $shop['allowmediacode'], 'radio');
				showsetting('forums_edit_posts_smilies', 'allowsmiliesnew', $shop['allowsmilies'], 'radio');
				showsetting('forums_edit_posts_jammer', 'jammernew', $shop['jammer'], 'radio');
				showsetting('forums_edit_posts_anonymous', 'allowanonymousnew', $shop['allowanonymous'], 'radio');
				showmultititle();
				showsetting('forums_edit_posts_disablethumb', 'disablethumbnew', $shop['disablethumb'], 'radio');
				showsetting('forums_edit_posts_disablewatermark', 'disablewatermarknew', $shop['disablewatermark'], 'radio');

				showsetting('forums_edit_posts_allowpostspecial', array(
						'allowpostspecialnew',
						array(
								cplang('thread_poll'),
								cplang('thread_trade'),
								cplang('thread_reward'),
								cplang('thread_activity'),
								cplang('thread_debate')
						)
				), $shop['allowpostspecial'], 'binmcheckbox');
				$threadpluginarray = '';
				if (is_array($_G['setting']['threadplugins']))
					foreach ($_G['setting']['threadplugins'] as $tpid=>$data){
						$threadpluginarray[] = array(
								$tpid,
								$data['name']
						);
					}
				if ($threadpluginarray){
					showsetting('forums_edit_posts_threadplugin', array(
							'threadpluginnew',
							$threadpluginarray
					), $shop['threadplugin'], 'mcheckbox');
				}
				showsetting('forums_edit_posts_allowspecialonly', 'allowspecialonlynew', $shop['allowspecialonly'], 'radio');
				showmultititle();
				showsetting('forums_edit_posts_autoclose', array(
						'autoclosenew',
						array(
								array(
										0,
										cplang('forums_edit_posts_autoclose_none'),
										array(
												'autoclose_time'=>'none'
										)
								),
								array(
										1,
										cplang('forums_edit_posts_autoclose_dateline'),
										array(
												'autoclose_time'=>''
										)
								),
								array(
										-1,
										cplang('forums_edit_posts_autoclose_lastpost'),
										array(
												'autoclose_time'=>''
										)
								)
						)
				), $shop['autoclose'], 'mradio');
				showtagheader('tbody', 'autoclose_time', $shop['autoclose'], 'sub');
				showsetting('forums_edit_posts_autoclose_time', 'autoclosetimenew', $shop['autoclosetime'], 'text');
				showtagfooter('tbody');
				showsetting('forums_edit_posts_attach_ext', 'attachextensionsnew', $shop['attachextensions'], 'text');
				showsetting('forums_edit_posts_allowfeed', 'allowfeednew', $shop['allowfeed'], 'radio');
				showsetting('forums_edit_posts_commentitem', 'commentitemnew', $shop['commentitem'], 'textarea');

				showtablefooter();
				showtagfooter('div');

				if (!$multiset){
					showtagheader('div', 'credits', $anchor == 'credits');
					showtableheader('forums_edit_credits_policy', 'fixpadding');
					echo '<tr class="header"><th>' . cplang('credits_id') . '</th><th>' . cplang('setting_credits_policy_cycletype') . '</th><th>' . cplang('setting_credits_policy_rewardnum') . '</th><th class="td25">' . cplang('custom') . '</th>';
					foreach ($_G['setting']['extcredits'] as $i=>$extcredit){
						echo '<th>' . $extcredit['title'] . '</th>';
					}
					echo '<th>&nbsp;</th></tr>';

					if (is_array($_G['setting']['extcredits'])){
						foreach ($rules as $rid=>$rule){
							$globalrule = $rule;
							$readonly = $checked = '';
							if (isset($shop['creditspolicy'][$rule['action']])){
								$rule = $shop['creditspolicy'][$rule['action']];
								$checked = ' checked="checked"';
							}else{
								for ($i = 1; $i <= 8; $i++){
									$rule['extcredits' . $i] = '';
								}
								$readonly = ' readonly="readonly" style="display:none;"';
							}
							$usecustom = '<input type="checkbox" name="usecustom[' . $rule['rid'] . ']" onclick="modifystate(this);" value="1" class="checkbox" ' . $checked . ' />';
							$tdarr = array(
									$rule['rulename'],
									$rule['rid'] ? cplang('setting_credits_policy_cycletype_' . $rule['cycletype']) : 'N/A',
									$rule['rid'] && $rule['cycletype'] ? $rule['rewardnum'] : 'N/A',
									$usecustom
							);

							for ($i = 1; $i <= 8; $i++){
								if ($_G['setting']['extcredits'][$i]){
									array_push($tdarr, '<input type="text" name="creditnew[' . $rule['rid'] . '][' . $i . ']" class="txt smtxt" value="' . $rule['extcredits' . $i] . '" ' . $readonly . ' /><span class="sml">(' . ($globalrule['extcredits' . $i]) . ')</span>');
								}
							}
							$opstr = '<a href="' . ADMINSCRIPT . '?action=credits&operation=edit&rid=' . $rule['rid'] . '&sid=' . $sid . '" title="" class="act">' . cplang('edit') . '</a>';
							array_push($tdarr, $opstr);
							showtablerow('', array_fill(4, count($_G['setting']['extcredits']) + 4, 'width="70"'), $tdarr);
						}

					}
					showtablerow('', 'class="lineheight" colspan="13"', cplang('forums_edit_credits_comment', array(
							'sid'=>$sid
					)));

					showtablefooter();
					print <<<EOF
					<script type="text/javascript">
						function modifystate(custom) {
							var trObj = custom.parentNode.parentNode;
							var inputsObj = trObj.getElementsByTagName('input');
							for(key in inputsObj) {
								var obj = inputsObj[key];
								if(typeof obj == 'object' && obj.type != 'checkbox') {
									obj.value = '';
									obj.readOnly = custom.checked ? false : true;
									obj.style.display = obj.readOnly ? 'none' : '';
								}
							}
						}
					</script>
EOF;
					showtagfooter('div');
				}

				if ($allowthreadtypes && !$multiset){
					$lang_forums_edit_threadtypes_use_cols = cplang('forums_edit_threadtypes_use_cols');
					$lang_forums_edit_threadtypes_use_choice = cplang('forums_edit_threadtypes_use_choice');
					echo <<<EOT
	<script type="text/JavaScript">
		var rowtypedata = [
			[
				[1,'', 'td25'],
				[1,'<input type="text" size="2" name="newdisplayorder[]" value="0" />'],
				[1,'<input type="text" name="newname[]" />'],
				[1,'<input type="text" name="newicon[]" />'],
				[1,'<input type="checkbox" class="checkbox" name="newenable[]" checked="checked" />'],
				[1,'<input type="checkbox" class="checkbox" name="newmoderators[]" value="1" />'],
				[1,'']
			],
		];
	</script>
EOT;
					showtagheader('div', 'threadtypes', $anchor == 'threadtypes');

					showtableheader('forums_edit_threadtypes_config', 'nobottom');
					showsetting('forums_edit_threadtypes_status', array(
							'threadtypesnew[status]',
							array(
									array(
											1,
											cplang('yes'),
											array(
													'threadtypes_config'=>'',
													'threadtypes_manage'=>''
											)
									),
									array(
											0,
											cplang('no'),
											array(
													'threadtypes_config'=>'none',
													'threadtypes_manage'=>'none'
											)
									)
							),
							TRUE
					), $shop['threadtypes']['status'], 'mradio');
					showtagheader('tbody', 'threadtypes_config', $shop['threadtypes']['status']);
					showsetting('forums_edit_threadtypes_required', 'threadtypesnew[required]', $shop['threadtypes']['required'], 'radio');
					showsetting('forums_edit_threadtypes_listable', 'threadtypesnew[listable]', $shop['threadtypes']['listable'], 'radio');
					showsetting('forums_edit_threadtypes_prefix', array(
							'threadtypesnew[prefix]',
							array(
									array(
											0,
											cplang('forums_edit_threadtypes_noprefix')
									),
									array(
											1,
											cplang('forums_edit_threadtypes_textonly')
									),
									array(
											2,
											cplang('forums_edit_threadtypes_icononly')
									)
							)
					), $shop['threadtypes']['prefix'], 'mradio');
					showtagfooter('tbody');
					showtablefooter();

					showtagheader('div', 'threadtypes_manage', $shop['threadtypes']['status']);
					showtableheader('forums_edit_threadtypes', 'noborder fixpadding');
					showsubtitle(array(
							'delete',
							'display_order',
							'forums_edit_threadtypes_name',
							'forums_edit_threadtypes_icon',
							'enable',
							'forums_edit_threadtypes_moderators'
					));
					echo $typeselect;
					echo '<tr><td colspan="7"><div><a href="###" onclick="addrow(this, 0)" class="addtr">' . cplang('threadtype_infotypes_add') . '</a></div></td></tr>';
					showtablefooter();
					showtagfooter('div');
					showtagfooter('div');

					showtagheader('div', 'threadsorts', $anchor == 'threadsorts');

					showtableheader('forums_edit_threadsorts', 'nobottom');
					showsetting('forums_edit_threadsorts_status', array(
							'threadsortsnew[status]',
							array(
									array(
											1,
											cplang('yes'),
											array(
													'threadsorts_config'=>'',
													'threadsorts_manage'=>''
											)
									),
									array(
											0,
											cplang('no'),
											array(
													'threadsorts_config'=>'none',
													'threadsorts_manage'=>'none'
											)
									)
							),
							TRUE
					), $shop['threadsorts']['status'], 'mradio');
					showtagheader('tbody', 'threadsorts_config', $shop['threadsorts']['status']);
					showsetting('forums_edit_threadtypes_required', 'threadsortsnew[required]', $shop['threadsorts']['required'], 'radio');
					showsetting('forums_edit_threadtypes_prefix', 'threadsortsnew[prefix]', $shop['threadsorts']['prefix'], 'radio');
					showsetting('forums_edit_threadsorts_default', 'threadsortsnew[default]', $shop['threadsorts']['default'], 'radio');
					showtagfooter('tbody');
					showtablefooter();

					showtagheader('div', 'threadsorts_manage', $shop['threadsorts']['status']);
					showtableheader('', 'noborder fixpadding');
					showsubtitle(array(
							'enable',
							'forums_edit_threadtypes_name',
							'forums_edit_threadtypes_note',
							'forums_edit_threadtypes_show',
							'forums_edit_threadtypes_defaultshow'
					));
					echo $sortselect;
					showtablefooter();
					showtagfooter('div');
					showtagfooter('div');
				}

				showtagheader('div', 'perm', $anchor == 'perm');
				showtableheader('forums_edit_perm_forum', 'nobottom');
				showsetting('forums_edit_perm_passwd', 'passwordnew', $shop['password'], 'text');
				showsetting('forums_edit_perm_users', 'formulapermusersnew', dstripslashes($shop['formulapermusers']), 'textarea');
				$colums = array();
				loadcache('medals');
				foreach ($_G['cache']['medals'] as $medalid=>$medal){
					$colums[] = array(
							$medalid,
							$medal['name']
					);
				}
				showtagheader('tbody', '', $_G['setting']['medalstatus']);
				showsetting('forums_edit_perm_medal', array(
						'medalnew',
						$colums
				), $shop['medal'], 'mcheckbox');
				showtagfooter('tbody');
				showtablefooter();

				if (!$multiset){
					showtableheader('forums_edit_perm_forum', 'noborder fixpadding');
					showsubtitle(array(
							'',
							'<input class="checkbox" type="checkbox" name="chkall1" onclick="checkAll(\'prefix\', this.form, \'^viewperm\', \'chkall1\')" id="chkall1" /><label for="chkall1"><br />' . cplang('forums_edit_perm_view') . '</label>',
							'<input class="checkbox" type="checkbox" name="chkall2" onclick="checkAll(\'prefix\', this.form, \'^postperm\', \'chkall2\')" id="chkall2" /><label for="chkall2"><br />' . cplang('forums_edit_perm_post') . '</label>',
							'<input class="checkbox" type="checkbox" name="chkall3" onclick="checkAll(\'prefix\', this.form, \'^replyperm\', \'chkall3\')" id="chkall3" /><label for="chkall3"><br />' . cplang('forums_edit_perm_reply') . '</label>',
							'<input class="checkbox" type="checkbox" name="chkall4" onclick="checkAll(\'prefix\', this.form, \'^getattachperm\', \'chkall4\')" id="chkall4" /><label for="chkall4"><br />' . cplang('forums_edit_perm_getattach') . '</label>',
							'<input class="checkbox" type="checkbox" name="chkall5" onclick="checkAll(\'prefix\', this.form, \'^postattachperm\', \'chkall5\')" id="chkall5" /><label for="chkall5"><br />' . cplang('forums_edit_perm_postattach') . '</label>',
							'<input class="checkbox" type="checkbox" name="chkall6" onclick="checkAll(\'prefix\', this.form, \'^postimageperm\', \'chkall6\')" id="chkall6" /><label for="chkall6"><br />' . cplang('forums_edit_perm_postimage') . '</label>'
					));

					$spviewgroup = array();
					foreach (array(
							'member',
							'special',
							'specialadmin',
							'system'
					) as $type){
						$tgroups = is_array($groups[$type]) ? $groups[$type] : array();
						showtablerow('', '', array(
								'<b>' . cplang('usergroups_' . $type) . '</b>'
						));
						foreach ($tgroups as $group){
							if ($group['groupid'] != 1){
								$spviewgroup[] = array(
										$group['groupid'],
										$group['grouptitle']
								);
							}
							$colums = array(
									'<input class="checkbox" title="' . cplang('select_all') . '" type="checkbox" name="chkallv' . $group['groupid'] . '" onclick="checkAll(\'value\', this.form, ' . $group['groupid'] . ', \'chkallv' . $group['groupid'] . '\')" id="chkallv_' . $group['groupid'] . '" /><label for="chkallv_' . $group['groupid'] . '"> ' . $group['grouptitle'] . '</label>'
							);
							foreach ($perms as $perm){
								$checked = strstr($shop[$perm], "\t$group[groupid]\t") ? 'checked="checked"' : NULL;
								$colums[] = '<input class="checkbox" type="checkbox" name="' . $perm . '[]" value="' . $group['groupid'] . '" chkvalue="' . $group['groupid'] . '" ' . $checked . '>';
							}
							showtablerow('', array(
									'width="21%"',
									'width="13%"',
									'width="13%"',
									'width="13%"',
									'width="16%"',
									'width="13%"',
									'width="13%"'
							), $colums);
						}
					}
					$showverify = true;
					foreach ($_G['setting']['verify'] as $vid=>$verify){
						if ($verify['available']){
							if ($showverify){
								showtablerow('', '', array(
										'<b>' . $lang['forums_edit_perm_verify'] . '</b>'
								));
								$showverify = false;
							}

							$colums = array(
									'<input class="checkbox" title="' . cplang('select_all') . '" type="checkbox" name="chkallverify' . $vid . '" onclick="checkAll(\'value\', this.form, \'verify' . $vid . '\', \'chkallverify' . $vid . '\')" id="chkallverify_' . $vid . '" /><label for="chkallverify_' . $vid . '"> ' . $verify['title'] . '</label>'
							);
							foreach ($perms as $perm){
								$checked = strstr($shop[$perm], "\tv$vid\t") ? 'checked="checked"' : NULL;
								$colums[] = '<input class="checkbox" type="checkbox" name="' . $perm . '[]" value="v' . $vid . '" chkvalue="verify' . $vid . '" ' . $checked . '>';
							}
							showtablerow('', array(
									'width="21%"',
									'width="13%"',
									'width="13%"',
									'width="13%"',
									'width="13%"',
									'width="13%"',
									'width="13%"'
							), $colums);
						}
					}
					showtablerow('', 'class="lineheight" colspan="6"', cplang('forums_edit_perm_shop_comment'));
					showtablefooter();

					showtableheader('forums_edit_perm_formula', 'fixpadding');
					$formulareplace .= '\'<u>' . cplang('setting_credits_formula_digestposts') . '</u>\',\'<u>' . cplang('setting_credits_formula_posts') . '</u>\'';

					?>
<script type="text/JavaScript">

		function isUndefined(variable) {
			return typeof variable == 'undefined' ? true : false;
		}

		function insertunit(text, textend) {
			$('formulapermnew').focus();
			textend = isUndefined(textend) ? '' : textend;
			if(!isUndefined($('formulapermnew').selectionStart)) {
				var opn = $('formulapermnew').selectionStart + 0;
				if(textend != '') {
					text = text + $('formulapermnew').value.substring($('formulapermnew').selectionStart, $('formulapermnew').selectionEnd) + textend;
				}
				$('formulapermnew').value = $('formulapermnew').value.substr(0, $('formulapermnew').selectionStart) + text + $('formulapermnew').value.substr($('formulapermnew').selectionEnd);
			} else if(document.selection && document.selection.createRange) {
				var sel = document.selection.createRange();
				if(textend != '') {
					text = text + sel.text + textend;
				}
				sel.text = text.replace(/\r?\n/g, '\r\n');
				sel.moveStart('character', -strlen(text));
			} else {
				$('formulapermnew').value += text;
			}
			formulaexp();
		}

		var formulafind = new Array('digestposts', 'posts');
		var formulareplace = new Array(<?php
					echo $formulareplace?>);
		function formulaexp() {
			var result = $('formulapermnew').value;
	<?php

					$extcreditsbtn = '';
					for ($i = 1; $i <= 8; $i++){
						$extcredittitle = $_G['setting']['extcredits'][$i]['title'] ? $_G['setting']['extcredits'][$i]['title'] : cplang('setting_credits_formula_extcredits') . $i;
						echo 'result = result.replace(/extcredits' . $i . '/g, \'<u>' . str_replace("'", "\'", $extcredittitle) . '</u>\');';
						$extcreditsbtn .= '<a href="###" onclick="insertunit(\'extcredits' . $i . '\')">' . $extcredittitle . '</a> &nbsp;';
					}

					$profilefields = '';
					$query = DB::query("SELECT * FROM " . DB::table('common_member_profile_setting') . " WHERE available='1' AND unchangeable='1'");
					while ($profilefield = DB::fetch($query)){
						echo 'result = result.replace(/' . $profilefield['fieldid'] . '/g, \'<u>' . str_replace("'", "\'", $profilefield['title']) . '</u>\');';
						$profilefields .= '<a href="###" onclick="insertunit(\' ' . $profilefield['fieldid'] . ' \')">&nbsp;' . $profilefield['title'] . '&nbsp;</a>&nbsp;';
					}

					echo 'result = result.replace(/regdate/g, \'<u>' . cplang('forums_edit_perm_formula_regdate') . '</u>\');';
					echo 'result = result.replace(/regday/g, \'<u>' . cplang('forums_edit_perm_formula_regday') . '</u>\');';
					echo 'result = result.replace(/regip/g, \'<u>' . cplang('forums_edit_perm_formula_regip') . '</u>\');';
					echo 'result = result.replace(/lastip/g, \'<u>' . cplang('forums_edit_perm_formula_lastip') . '</u>\');';
					echo 'result = result.replace(/buyercredit/g, \'<u>' . cplang('forums_edit_perm_formula_buyercredit') . '</u>\');';
					echo 'result = result.replace(/sellercredit/g, \'<u>' . cplang('forums_edit_perm_formula_sellercredit') . '</u>\');';
					echo 'result = result.replace(/digestposts/g, \'<u>' . cplang('setting_credits_formula_digestposts') . '</u>\');';
					echo 'result = result.replace(/posts/g, \'<u>' . cplang('setting_credits_formula_posts') . '</u>\');';
					echo 'result = result.replace(/threads/g, \'<u>' . cplang('setting_credits_formula_threads') . '</u>\');';
					echo 'result = result.replace(/oltime/g, \'<u>' . cplang('setting_credits_formula_oltime') . '</u>\');';
					echo 'result = result.replace(/and/g, \'&nbsp;&nbsp;<b>' . cplang('forums_edit_perm_formula_and') . '</b>&nbsp;&nbsp;\');';
					echo 'result = result.replace(/or/g, \'&nbsp;&nbsp;<b>' . cplang('forums_edit_perm_formula_or') . '</b>&nbsp;&nbsp;\');';
					echo 'result = result.replace(/>=/g, \'&ge;\');';
					echo 'result = result.replace(/<=/g, \'&le;\');';
					echo 'result = result.replace(/==/g, \'=\');';

					?>
			$('formulapermexp').innerHTML = result;
		}
	</script>
<tr>
	<td colspan="2">
	<div class="extcredits">
	<?php
					echo $extcreditsbtn;
					?>
	<a href="###" onclick="insertunit(' regdate ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_regdate')?>&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' regday ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_regday')?>&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' regip ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_regip')?>&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' lastip ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_lastip')?>&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' buyercredit ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_buyercredit')?>&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' sellercredit ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_sellercredit')?>&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' digestposts ')"><?php
					echo cplang('forums_edit_perm_formula_digestposts')?></a>&nbsp;
	<a href="###" onclick="insertunit(' posts ')"><?php
					echo cplang('forums_edit_perm_formula_posts')?></a>&nbsp;
	<a href="###" onclick="insertunit(' threads ')"><?php
					echo cplang('forums_edit_perm_formula_threads')?></a>&nbsp;
	<a href="###" onclick="insertunit(' oltime ')"><?php
					echo cplang('forums_edit_perm_formula_oltime')?></a>&nbsp;
	<a href="###" onclick="insertunit(' + ')">&nbsp;+&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' - ')">&nbsp;-&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' * ')">&nbsp;*&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' / ')">&nbsp;/&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' > ')">&nbsp;>&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' >= ')">&nbsp;>=&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' < ')">&nbsp;<&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' <= ')">&nbsp;<=&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' == ')">&nbsp;=&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' != ')">&nbsp;!=&nbsp;</a>&nbsp; <a
		href="###" onclick="insertunit(' (', ') ')">&nbsp;(&nbsp;)&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' and ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_and')?>&nbsp;</a>&nbsp;
	<a href="###" onclick="insertunit(' or ')">&nbsp;<?php
					echo cplang('forums_edit_perm_formula_or')?>&nbsp;</a>&nbsp;<br />
	<?php
					echo $profilefields;
					?>

	<div id="formulapermexp" class="margintop marginbot diffcolor2"><?php
					echo $formulapermexp?></div>
	</div>
	<textarea name="formulapermnew" id="formulapermnew" class="marginbot"
		style="width: 80%" rows="3" onkeyup="formulaexp()"><?php
					echo dhtmlspecialchars($shop['formulaperm'])?></textarea>
	<script type="text/JavaScript">formulaexp()</script> <br />
	<span class="smalltxt"><?php
					cplang('forums_edit_perm_formula_comment', null, true);
					?></span>
	</td>
</tr>
<?php

					showtablefooter();
					showtableheader('', 'noborder fixpadding');
					$shop['spviewperm'] = explode("\t", $shop['spviewperm']);
					showsetting('forums_edit_perm_spview', array(
							'spviewpermnew',
							$spviewgroup
					), $shop['spviewperm'], 'mcheckbox');
					showsetting('forums_edit_perm_formulapermmessage', 'formulapermmessagenew', $shop['formulapermmessage'], 'textarea');
					showtablefooter();

				}
				if ($pluginsetting){
					showtagfooter('div');
					showtagheader('div', 'plugin', $anchor == 'plugin');
					showtableheader('', 'noborder fixpadding');
					foreach ($pluginsetting as $setting){
						showtitle($setting['name']);
						foreach ($setting['setting'] as $varid=>$var){
							if ($var['type'] != 'select'){
								showsetting($var['title'], 'pluginnew[' . $varid . ']', $shop['plugin'][$varid], $var['type'], '', 0, $var['description']);
							}else{
								showsetting($var['title'], array(
										'pluginnew[' . $varid . ']',
										$var['select']
								), $shop['plugin'][$varid], $var['type'], '', 0, $var['description']);
							}
						}
					}
					showtablefooter();
				}

				showtagfooter('div');

				showtableheader('', 'notop');
				showsubmit('detailsubmit', 'submit');
				showtablefooter();
				$_G['showsetting_multi']++;
			}
		}

		if ($_G['showsetting_multicount'] > 1){
			showhiddenfields(array(
					'multi'=>implode(',', $msids)
			));
			showmulti();
		}

		showformfooter();

	}else{

		if (!$multiset){
			$_G['gp_multinew'] = array(
					0=>array(
							'single'=>1
					)
			);
		}
		$pluginvars = array();
		require_once libfile('function/delete');
		foreach ($_G['gp_multinew'] as $k=>$row){
			if (empty($row['single'])){
				foreach ($row as $key=>$value){
					$_G['gp_' . $key] = $value;
				}
				$sid = $_G['gp_multi'][$k];
			}
			$shop = $mshop[$k];

			if (strlen($_G['gp_namenew']) > 50){
				cpmsg('forums_name_toolong', '', 'error');
			}

			if (!$multiset){
				if (!checkformulaperm($_G['gp_formulapermnew'])){
					cpmsg('forums_formulaperm_error', '', 'error');
				}

				$formulapermary[0] = $_G['gp_formulapermnew'];
				$formulapermary[1] = preg_replace(array(
						"/(digestposts|posts|threads|oltime|extcredits[1-8])/",
						"/(regdate|regday|regip|lastip|buyercredit|sellercredit|field\d+)/"
				), array(
						"getuserprofile('\\1')",
						"\$memberformula['\\1']"
				), $_G['gp_formulapermnew']);
				$formulapermary['message'] = $_G['gp_formulapermmessagenew'];
			}else{
				$formulapermary = unserialize($shop['formulaperm']);
			}
			$formulapermary['medal'] = $_G['gp_medalnew'];
			$formulapermary['users'] = $_G['gp_formulapermusersnew'];
			$_G['gp_formulapermnew'] = addslashes(serialize($formulapermary));

			$domain = '';
			if (!empty($_G['gp_domainnew']) && !empty($_G['setting']['domain']['root']['shops'])){
				$domain = strtolower(trim($_G['gp_domainnew']));
			}
			require_once libfile('function/discuzcode');
			if ($_G['gp_type'] == 'group'){
				if ($_G['gp_namenew']){
					$newstyleid = intval($_G['gp_styleidnew']);
					$shopcolumnsnew = $_G['gp_forumcolumnsnew'] > 1 ? intval($_G['gp_forumcolumnsnew']) : 0;
					$catshopcolumnsnew = $_G['gp_catforumcolumnsnew'] > 1 ? intval($_G['gp_catforumcolumnsnew']) : 0;
					$descriptionnew = addslashes(preg_replace('/on(mousewheel|mouseover|click|load|onload|submit|focus|blur)="[^"]*"/i', '', discuzcode(dstripslashes($_G['gp_descriptionnew']), 1, 0, 0, 0, 1, 1, 0, 0, 1)));
					if (!empty($_G['setting']['domain']['root']['shops'])){
						deletedomain($sid, 'subarea');
						if (!empty($domain)){
							domaincheck($domain, $_G['setting']['domain']['root']['shops'], 1, 0);
							DB::insert('common_domain', array(
									'domain'=>$domain,
									'domainroot'=>$_G['setting']['domain']['root']['shops'],
									'id'=>$sid,
									'idtype'=>'subarea'
							));
						}
					}
					DB::update('shop_category', array(
							'name'=>$_G['gp_namenew'],
							'shopcolumns'=>$shopcolumnsnew,
							'catshopcolumns'=>$catshopcolumnsnew,
							'domain'=>$domain,
							'status'=>intval($_G['gp_statusnew']),
							'hot'=>intval($_G['gp_cathot']),
							'compare'=>intval($_G['gp_compare']),
							'styleid'=>$newstyleid
					), "sid='$sid'");

					$extranew = is_array($_G['gp_extranew']) ? $_G['gp_extranew'] : array();
					$extranew = serialize($extranew);
					DB::update('shop_shopfield', array(
							'extra'=>$extranew,
							'description'=>$descriptionnew,
							'seotitle'=>$_G['gp_seotitlenew'],
							'keywords'=>$_G['gp_keywordsnew'],
							'seodescription'=>$_G['gp_seodescriptionnew']
					), "sid='$sid'");

					loadcache('shops');
					$subsids = array();
					get_subsids($sid);

					if ($newstyleid != $mshop[0]['styleid'] && !empty($subsids)){
						DB::update('shop_category', array(
								'styleid'=>$newstyleid
						), "sid IN (" . dimplode($subsids) . ")");
					}

					updatecache('shops');

					cpmsg('forums_edit_succeed', 'action=shops', 'succeed');
				}else{
					cpmsg('forums_edit_name_invalid', '', 'error');
				}

			}else{
				$extensionarray = array();
				foreach (explode(',', $_G['gp_attachextensionsnew']) as $extension){
					if ($extension = trim($extension)){
						$extensionarray[] = $extension;
					}
				}
				$_G['gp_attachextensionsnew'] = implode(', ', $extensionarray);

				foreach ($perms as $perm){
					$_G['gp_' . $perm . 'new'] = is_array($_G['gp_' . $perm]) && !empty($_G['gp_' . $perm]) ? "\t" . implode("\t", $_G['gp_' . $perm]) . "\t" : '';
				}

				$supadd = '';
				$shopdata = $shopfielddata = array();
				if ($_G['gp_supnew'] != $shop['sup'] && !$multiset){
					$query = DB::query("SELECT sid FROM " . DB::table('shop_category') . " WHERE sup='$sid'");
					if (DB::num_rows($query)){
						cpmsg('forums_edit_sub_notnull', '', 'error');
					}

					$sup = DB::fetch_first("SELECT sid, type, inheritedmod FROM " . DB::table('shop_category') . " WHERE sid='{$_G['gp_supnew']}'");

					$supadd = ", type='" . ($sup['type'] == 'shop' ? 'sub' : 'shop') . "', sup='$sup[sid]'";
					$shopdata['type'] = $sup['type'] == 'shop' ? 'sub' : 'shop';
					$shopdata['sup'] = $sup['sid'];
					DB::query("DELETE FROM " . DB::table('shop_moderator') . " WHERE sid='$sid' AND inherited='1'");
					$query = DB::query("SELECT * FROM " . DB::table('shop_moderator') . " WHERE sid='{$_G['gp_supnew']}' " . ($sup['inheritedmod'] ? '' : "AND inherited='1'"));
					while ($mod = DB::fetch($query)){
						DB::query("REPLACE INTO " . DB::table('shop_moderator') . " (uid, sid, displayorder, inherited)
								VALUES ('$mod[uid]', '$sid', '0', '1')");
					}

					$moderators = $tab = '';
					$query = DB::query("SELECT m.username FROM " . DB::table('common_member') . " m, " . DB::table('shop_moderator') . " mo WHERE mo.sid='$sid' AND mo.inherited='0' AND m.uid=mo.uid ORDER BY mo.displayorder");
					while ($mod = DB::fetch($query)){
						$moderators .= $tab . addslashes($mod['username']);
						$tab = "\t";
					}
					DB::update('shop_shopfield', array(
							'moderators'=>$moderators
					), "sid='$sid'");
				}

				$allowpostspecialtrade = intval($_G['gp_allowpostspecialnew'][2]);
				$_G['gp_allowpostspecialnew'] = bindec(intval($_G['gp_allowpostspecialnew'][6]) . intval($_G['gp_allowpostspecialnew'][5]) . intval($_G['gp_allowpostspecialnew'][4]) . intval($_G['gp_allowpostspecialnew'][3]) . intval($_G['gp_allowpostspecialnew'][2]) . intval($_G['gp_allowpostspecialnew'][1]));
				$allowspecialonlynew = $_G['gp_allowpostspecialnew'] || $_G['setting']['threadplugins'] && $_G['gp_threadpluginnew'] ? $_G['gp_allowspecialonlynew'] : 0;
				$shopcolumnsnew = $_G['gp_forumcolumnsnew'] > 1 ? intval($_G['gp_forumcolumnsnew']) : 0;
				$threadcachesnew = max(0, min(100, intval($_G['gp_threadcachesnew'])));
				$subforumsindexnew = $_G['gp_subforumsindexnew'] == -1 ? 0 : ($_G['gp_subforumsindexnew'] == 0 ? 2 : 1);
				$_G['gp_simplenew'] = isset($_G['gp_simplenew']) ? $_G['gp_simplenew'] : 0;
				$simplenew = bindec(sprintf('%02d', decbin($_G['gp_defaultorderfieldnew'])) . $_G['gp_defaultordernew'] . sprintf('%02d', decbin($subforumsindexnew)) . '00' . $_G['gp_simplenew']);
				$allowglobalsticknew = $_G['gp_allowglobalsticknew'] ? 1 : 0;

				if (!empty($_G['setting']['domain']['root']['shops'])){
					deletedomain($sid, 'shop');
					if (!empty($domain)){
						domaincheck($domain, $_G['setting']['domain']['root']['shops'], 1, 0);
						DB::insert('common_domain', array(
								'domain'=>$domain,
								'domainroot'=>addslashes($_G['setting']['domain']['root']['shops']),
								'id'=>$sid,
								'idtype'=>'shop'
						));
					}
				}
				$shopdata = array_merge($shopdata, array(
						'status'=>$_G['gp_statusnew'],
						'hot'=>$_G['gp_cathot'],
						'compare'=>$_G['gp_compare'],
						'name'=>$_G['gp_namenew'],
						'styleid'=>$_G['gp_styleidnew'],
						'alloweditpost'=>$_G['gp_alloweditpostnew'],
						'allowappend'=>$_G['gp_allowappendnew'],
						'allowpostspecial'=>$_G['gp_allowpostspecialnew'],
						'allowspecialonly'=>$allowspecialonlynew,
						'allowhtml'=>$_G['gp_allowhtmlnew'],
						'allowbbcode'=>$_G['gp_allowbbcodenew'],
						'allowimgcode'=>$_G['gp_allowimgcodenew'],
						'allowmediacode'=>$_G['gp_allowmediacodenew'],
						'allowsmilies'=>$_G['gp_allowsmiliesnew'],
						'alloweditrules'=>$_G['gp_alloweditrulesnew'],
						'allowside'=>$_G['gp_allowsidenew'],
						'modnewposts'=>$_G['gp_modnewpostsnew'],
						'recyclebin'=>$_G['gp_recyclebinnew'],
						'jammer'=>$_G['gp_jammernew'],
						'allowanonymous'=>$_G['gp_allowanonymousnew'],
						'shopcolumns'=>$shopcolumnsnew,
						'catshopcolumns'=>$catshopcolumnsnew,
						'threadcaches'=>$threadcachesnew,
						'simple'=>$simplenew,
						'allowglobalstick'=>$allowglobalsticknew,
						'disablethumb'=>$_G['gp_disablethumbnew'],
						'disablewatermark'=>$_G['gp_disablewatermarknew'],
						'autoclose'=>intval($_G['gp_autoclosenew'] * $_G['gp_autoclosetimenew']),
						'allowfeed'=>$_G['gp_allowfeednew'],
						'domain'=>$domain
				));
				DB::update('shop_category', $shopdata, "sid='$sid'");

				$query = DB::query("SELECT sid FROM " . DB::table('shop_shopfield') . " WHERE sid='$sid'");
				if (!(DB::num_rows($query))){
					DB::insert('shop_shopfield', array(
							'sid'=>$sid
					));
				}

				if (!$multiset){
					$creditspolicynew = array();
					$creditspolicy = $shop['creditspolicy'] ? unserialize($shop['creditspolicy']) : array();
					foreach ($_G['gp_creditnew'] as $rid=>$rule){
						$creditspolicynew[$rules[$rid]['action']] = isset($creditspolicy[$rules[$rid]['action']]) ? $creditspolicy[$rules[$rid]['action']] : $rules[$rid];
						$usedefault = $_G['gp_usecustom'][$rid] ? false : true;

						if (!$usedefault){
							foreach ($rule as $i=>$v){
								$creditspolicynew[$rules[$rid]['action']]['extcredits' . $i] = is_numeric($v) ? intval($v) : 0;
							}
						}

						$cpsids = explode(',', $rules[$rid]['sids']);
						$cpsidsnew = array();
						foreach ($cpsids as $cpsid){
							if (!$cpsid){
								continue;
							}
							if ($cpsid != $sid){
								$cpsidsnew[] = $cpsid;
							}
						}
						if (!$usedefault){
							$cpsidsnew[] = $sid;
							$creditspolicynew[$rules[$rid]['action']]['sids'] = $rules[$rid]['sids'] = implode(',', $cpsidsnew);
						}else{
							$rules[$rid]['sids'] = implode(',', $cpsidsnew);
							unset($creditspolicynew[$rules[$rid]['action']]);
						}

	//					DB::update('common_credit_rule', array('sids' => $rules[$rid]['sids']), array('rid' => $rid));
					}
					$shopfielddata = array();
					$shopfielddata['creditspolicy'] = addslashes(serialize($creditspolicynew));

					$threadtypesnew = $_G['gp_threadtypesnew'];
					$threadtypesnew['types'] = $threadtypes['special'] = $threadtypes['show'] = array();
					$threadsortsnew['types'] = $threadsorts['special'] = $threadsorts['show'] = array();

					if ($allowthreadtypes){
						if (is_array($_G['gp_newname']) && $_G['gp_newname']){
							$newname = array_unique($_G['gp_newname']);
							if ($newname){
								foreach ($newname as $key=>$val){
									$newname[$key] = $val = strip_tags(trim(str_replace(array(
											"'",
											"\""
									), array(), $val)), "<font><span><b><strong>");
									if ($_G['gp_newenable'][$key] && $val){
										$newtypeid = DB::result_first("SELECT typeid FROM " . DB::table('shop_threadclass') . " WHERE sid='$sid' AND name='$val'");
										if (!$newtypeid){
											$threadtypes_newdisplayorder = intval($_G['gp_newdisplayorder'][$key]);
											$threadtypes_newicon = trim($_G['gp_newicon'][$key]);
											$newtypeid = DB::insert('shop_threadclass', array(
													'sid'=>$sid,
													'name'=>$val,
													'displayorder'=>$threadtypes_newdisplayorder,
													'icon'=>$threadtypes_newicon,
													'moderators'=>intval($_G['gp_newmoderators'][$key])
											), 1);
										}
										$threadtypesnew['options']['name'][$newtypeid] = $val;
										$threadtypesnew['options']['icon'][$newtypeid] = $threadtypes_newicon;
										$threadtypesnew['options']['displayorder'][$newtypeid] = $threadtypes_newdisplayorder;
										$threadtypesnew['options']['enable'][$newtypeid] = 1;
										$threadtypesnew['options']['moderators'][$newtypeid] = $_G['gp_newmoderators'][$key];
									}
								}
							}
							$threadtypesnew['status'] = 1;
						}else{
							$newname = array();
						}
						if ($threadtypesnew['status']){
							if (is_array($threadtypesnew['options']) && $threadtypesnew['options']){
								if (!empty($threadtypesnew['options']['enable'])){
									$typeids = dimplode(array_keys($threadtypesnew['options']['enable']));
								}else{
									$typeids = '0';
								}
								$query = DB::query("SELECT * FROM " . DB::table('shop_threadclass') . " WHERE typeid IN ($typeids) ORDER BY displayorder");
								while ($type = DB::fetch($query)){
									if ($threadtypesnew['options']['name'][$type['typeid']] != $type['name'] || $threadtypesnew['options']['displayorder'][$type['typeid']] != $type['displayorder'] || $threadtypesnew['options']['icon'][$type['typeid']] != $type['icon'] || $threadtypesnew['options']['moderators'][$type['typeid']] != $type['moderators']){
										$threadtypesnew['options']['name'][$type['typeid']] = strip_tags(trim(str_replace(array(
												"'",
												"\""
										), array(), $threadtypesnew['options']['name'][$type['typeid']])), "<font><span><b><strong>");
										DB::update('shop_threadclass', array(
												'name'=>$threadtypesnew['options']['name'][$type['typeid']],
												'displayorder'=>$threadtypesnew['options']['displayorder'][$type['typeid']],
												'icon'=>$threadtypesnew['options']['icon'][$type['typeid']],
												'moderators'=>$threadtypesnew['options']['moderators'][$type['typeid']]
										), "typeid='{$type['typeid']}'");
									}
								}
								if (!empty($threadtypesnew['options']['delete'])){
									$threadtypes_deleteids = dimplode($threadtypesnew['options']['delete']);
									DB::query("DELETE FROM " . DB::table('shop_threadclass') . " WHERE `typeid` IN ($threadtypes_deleteids)");
								}
							}
						}else{
							$threadtypesnew = '';
						}
						if ($threadtypesnew && $typeids){
							$query = DB::query("SELECT * FROM " . DB::table('shop_threadclass') . " WHERE typeid IN ($typeids) ORDER BY displayorder");
							while ($type = DB::fetch($query)){
								if ($threadtypesnew['options']['enable'][$type['typeid']]){
									$threadtypesnew['types'][$type['typeid']] = $threadtypesnew['options']['name'][$type['typeid']];
								}
								$threadtypesnew['icons'][$type['typeid']] = trim($threadtypesnew['options']['icon'][$type['typeid']]);
								$threadtypesnew['moderators'][$type['typeid']] = $threadtypesnew['options']['moderators'][$type['typeid']];
							}
							$threadtypesnew = $threadtypesnew['types'] ? addslashes(serialize(array(
									'required'=>(bool)$threadtypesnew['required'],
									'listable'=>(bool)$threadtypesnew['listable'],
									'prefix'=>$threadtypesnew['prefix'],
									'types'=>$threadtypesnew['types'],
									'icons'=>$threadtypesnew['icons'],
									'moderators'=>$threadtypesnew['moderators']
							))) : '';
						}
						$shopfielddata['threadtypes'] = $threadtypesnew;

						$threadsortsnew = $_G['gp_threadsortsnew'];
						if ($threadsortsnew['status']){
							if (is_array($threadsortsnew['options']) && $threadsortsnew['options']){
								if (!empty($threadsortsnew['options']['enable'])){
									$sortids = dimplode(array_keys($threadsortsnew['options']['enable']));
								}else{
									$sortids = '0';
								}

								$query = DB::query("SELECT * FROM " . DB::table('shop_threadtype') . " WHERE typeid IN ($sortids) ORDER BY displayorder");
								while ($sort = DB::fetch($query)){
									if ($threadsortsnew['options']['enable'][$sort['typeid']]){
										$threadsortsnew['types'][$sort['typeid']] = $sort['name'];
									}
									$threadsortsnew['expiration'][$sort['typeid']] = $sort['expiration'];
									$threadsortsnew['description'][$sort['typeid']] = $sort['description'];
									$threadsortsnew['show'][$sort['typeid']] = $threadsortsnew['options']['show'][$sort['typeid']] ? 1 : 0;
								}
							}

							if ($threadsortsnew['default'] && !$threadsortsnew['defaultshow']){
								cpmsg('forums_edit_threadsort_nonexistence', '', 'error');
							}

							$threadsortsnew = $threadsortsnew['types'] ? addslashes(serialize(array(
									'required'=>(bool)$threadsortsnew['required'],
									'prefix'=>(bool)$threadsortsnew['prefix'],
									'types'=>$threadsortsnew['types'],
									'show'=>$threadsortsnew['show'],
									'expiration'=>$threadsortsnew['expiration'],
									'description'=>$threadsortsnew['description'],
									'defaultshow'=>$threadsortsnew['default'] ? $threadsortsnew['defaultshow'] : '',
									'templatelist'=>$threadsortsnew['templatelist']
							))) : '';
						}else{
							$threadsortsnew = '';
						}

						$shopfielddata['threadsorts'] = $threadsortsnew;

					}
				}

				$threadpluginnew = addslashes(serialize($_G['gp_threadpluginnew']));
				$modrecommendnew = $_G['gp_modrecommendnew'];
				$modrecommendnew['num'] = $modrecommendnew['num'] ? intval($modrecommendnew['num']) : 10;
				$modrecommendnew['cachelife'] = intval($modrecommendnew['cachelife']);
				$modrecommendnew['maxlength'] = $modrecommendnew['maxlength'] ? intval($modrecommendnew['maxlength']) : 0;
				$modrecommendnew['dateline'] = $modrecommendnew['dateline'] ? intval($modrecommendnew['dateline']) : 0;
				$modrecommendnew['imagenum'] = $modrecommendnew['imagenum'] ? intval($modrecommendnew['imagenum']) : 0;
				$modrecommendnew['imagewidth'] = $modrecommendnew['imagewidth'] ? intval($modrecommendnew['imagewidth']) : 300;
				$modrecommendnew['imageheight'] = $modrecommendnew['imageheight'] ? intval($modrecommendnew['imageheight']) : 250;
				$modrecommendnew = $modrecommendnew && is_array($modrecommendnew) ? addslashes(serialize($modrecommendnew)) : '';
				$descriptionnew = addslashes(preg_replace('/on(mousewheel|mouseover|click|load|onload|submit|focus|blur)="[^"]*"/i', '', discuzcode(dstripslashes($_G['gp_descriptionnew']), 1, 0, 0, 0, 1, 1, 0, 0, 1)));
				$rulesnew = addslashes(preg_replace('/on(mousewheel|mouseover|click|load|onload|submit|focus|blur)="[^"]*"/i', '', discuzcode(dstripslashes($_G['gp_rulesnew']), 1, 0, 0, 0, 1, 1, 0, 0, 1)));
				$extranew = is_array($_G['gp_extranew']) ? $_G['gp_extranew'] : array();
				$shop['extra'] = unserialize($shop['extra']);
				$shop['extra']['namecolor'] = $extranew['namecolor'];

				if (!$multiset){
					if ($_FILES['bannernew']){
						$bannernew = upload_icon_banner($shop, $_FILES['bannernew'], 'banner');
					}else{
						$bannernew = $_G['gp_bannernew'];
					}
					if ($bannernew){
						$shopfielddata['banner'] = $bannernew;
					}
					if ($_G['gp_deletebanner'] && $shop['banner']){
						$valueparse = parse_url($shop['banner']);
						if (!isset($valueparse['host'])){
							@unlink($_G['setting']['attachurl'] . 'common/' . $shop['banner']);
						}
						$shopfielddata['banner'] = '';
					}

					if ($_FILES['iconnew']){
						$iconnew = upload_icon_banner($shop, $_FILES['iconnew'], 'icon');
					}else{
						$iconnew = $_G['gp_iconnew'];
					}
					if ($iconnew){
						$shopfielddata['icon'] = $iconnew;
						if (!$extranew['iconwidth']){
							$valueparse = parse_url($shopfielddata['icon']);
							if (!isset($valueparse['host'])){
								$iconnew = $_G['setting']['attachurl'] . 'common/' . $shopfielddata['icon'];
							}
							if ($info = @getimagesize($iconnew)){
								$extranew['iconwidth'] = $info[0];
							}
						}
						$shop['extra']['iconwidth'] = $extranew['iconwidth'];
					}else{
						$shop['extra']['iconwidth'] = '';
					}
					if ($_G['gp_deleteicon']){
						$valueparse = parse_url($shop['icon']);
						if (!isset($valueparse['host'])){
							@unlink($_G['setting']['attachurl'] . 'common/' . $shop['icon']);
						}
						$shopfielddata['icon'] = '';
						$shop['extra']['iconwidth'] = '';
					}
				}

				$extranew = serialize($shop['extra']);

				$shopfielddata = array_merge($shopfielddata, array(
						'description'=>$descriptionnew,
						'password'=>$_G['gp_passwordnew'],
						'redirect'=>$_G['gp_redirectnew'],
						'rules'=>$rulesnew,
						'attachextensions'=>$_G['gp_attachextensionsnew'],
						'modrecommend'=>$modrecommendnew,
						'seotitle'=>$_G['gp_seotitlenew'],
						'keywords'=>$_G['gp_keywordsnew'],
						'seodescription'=>$_G['gp_seodescriptionnew'],
						'threadplugin'=>$threadpluginnew,
						'extra'=>$extranew,
						'commentitem'=>$_G['gp_commentitemnew'],
						'formulaperm'=>$_G['gp_formulapermnew'],
						'picstyle'=>$_G['gp_picstylenew'],
						'widthauto'=>$_G['gp_widthautonew']
				));
				if (!$multiset){
					$shopfielddata = array_merge($shopfielddata, array(
							'viewperm'=>$_G['gp_viewpermnew'],
							'postperm'=>$_G['gp_postpermnew'],
							'replyperm'=>$_G['gp_replypermnew'],
							'getattachperm'=>$_G['gp_getattachpermnew'],
							'postattachperm'=>$_G['gp_postattachpermnew'],
							'postimageperm'=>$_G['gp_postimagepermnew'],
							'relatedgroup'=>$_G['gp_relatedgroupnew'],
							'spviewperm'=>implode("\t", $_G['gp_spviewpermnew'])
					));
				}
				if ($shopfielddata){
					DB::update('shop_shopfield', $shopfielddata, "sid='$sid'");
				}
				if ($pluginsetting){
					foreach ($_G['gp_pluginnew'] as $pluginvarid=>$value){
						$pluginvars[$pluginvarid][$sid] = $value;
					}
				}

				if ($modrecommendnew && !$modrecommendnew['sort']){
					require_once libfile('function/shoplist');
					recommendupdate($sid, $modrecommendnew, '1');
				}

				if ($shopkeys[$sid] != $_G['gp_keysnew'] && preg_match('/^\w*$/', $_G['gp_keysnew']) && !preg_match('/^\d+$/', $_G['gp_keysnew'])){
					$shopkeys[$sid] = $_G['gp_keysnew'];
					DB::query("REPLACE INTO " . DB::table('common_setting') . " (skey, svalue) VALUES ('forumkeys', '" . (addslashes(serialize($shopkeys))) . "')");
				}

			}
			if (empty($row['single'])){
				foreach ($row as $key=>$value){
					unset($_G['gp_' . $key]);
				}
			}
		}

		if ($pluginvars){
			set_pluginsetting($pluginvars);
		}

		updatecache(array(
				'shops',
				'setting',
				'creditrule'
		));
		cpmsg('forums_edit_succeed', "mod=shop&action=shops&operation=edit&" . ($multiset ? 'multi=' . implode(',', $_G['gp_multi']) : "sid=$sid") . ($_G['gp_anchor'] ? "&anchor={$_G['gp_anchor']}" : ''), 'succeed');

	}

}elseif ($operation == 'delete'){
	$ajax = $_G['gp_ajax'];
	$confirmed = $_G['gp_confirmed'];
	$finished = $_G['gp_finished'];
	$total = intval($_G['gp_total']);
	$pp = intval($_G['gp_pp']);
	$currow = intval($_G['gp_currow']);

	if ($_G['gp_ajax']){
		ob_end_clean();
		require_once libfile('function/post');
		$tids = array();

		$query = DB::query("SELECT sup FROM " . DB::table('shop_category') . " WHERE sid='$sid' LIMIT $pp");
		while ($thread = DB::fetch($query)){
			$tids[] = $thread['sup'];
		}
		require_once libfile('function/delete');
		delete_shop_category($tids);

		deletedomain($sid, 'shops');
		deletedomain($sid, 'subarea');
		if ($currow + $pp > $total){
			//my_thread_log('del_shop_category', array('sid' => $sid));
			DB::query("DELETE FROM " . DB::table('shop_category') . " WHERE sid='$sid'");
			DB::query("DELETE FROM " . DB::table('shop_moderator') . " WHERE sid='$sid'");
			echo 'TRUE';
			exit();
		}

		echo 'GO';
		exit();

	}else{

		if ($_G['gp_finished']){
			updatecache('shops');
			cpmsg('shop_delete_succeed', 'action=shops', 'succeed');

		}

		if (DB::result_first("SELECT COUNT(*) FROM " . DB::table('shop_category') . " WHERE sup='$sid'")){
			cpmsg('shop_delete_sub_notnull', '', 'error');
		}

		if (!$_G['gp_confirmed']){

			cpmsg('forums_delete_confirm', "action=shops&operation=delete&sid=$sid", 'form');

		}else{

			$threads = DB::result_first("SELECT COUNT(*) FROM " . DB::table('shop_category') . " WHERE sid='$sid'");

			cpmsg('forums_delete_alarm', "action=shops&operation=delete&sid=$sid&confirmed=1", 'loadingform', '', '<div id="percent">0%</div>', FALSE);

			echo "
			<div id=\"statusid\" style=\"display:none\"></div>
			<script type=\"text/JavaScript\">
				var xml_http_building_link = '" . cplang('xml_http_building_link') . "';
				var xml_http_sending = '" . cplang('xml_http_sending') . "';
				var xml_http_loading = '" . cplang('xml_http_loading') . "';
				var xml_http_load_failed = '" . cplang('xml_http_load_failed') . "';
				var xml_http_data_in_processed = '" . cplang('xml_http_data_in_processed') . "';
				var adminfilename = '" . ADMINSCRIPT . "';
				function forumsdelete(url, total, pp, currow) {

					var x = new Ajax('HTML', 'statusid');
					x.get(url+'&ajax=1&pp='+pp+'&total='+total+'&currow='+currow, function(s) {
						if(s != 'GO') {
							location.href = adminfilename + '?action=shops&operation=delete&finished=1';
						}

						currow += pp;
						var percent = ((currow / total) * 100).toFixed(0);
						percent = percent > 100 ? 100 : percent;
						document.getElementById('percent').innerHTML = percent+'%';
						document.getElementById('percent').style.backgroundPosition = '-'+percent+'%';

						if(currow < total) {
							forumsdelete(url, total, pp, currow);
						}
					});
				}
				forumsdelete(adminfilename + '?action=shops&operation=delete&sid=$sid&confirmed=1', $threads, 2000, 0);
			</script>
			";
		}
	}

}elseif ($operation == 'param' && $sid){
	$mshop = array();
	$query = DB::query("SELECT *
						FROM " . DB::table('shop_category') . "
						WHERE sid = $sid");

	if (!DB::num_rows($query)){
		cpmsg('shop_nonexistence', '', 'error');
	}else{
		while ($shop = DB::fetch($query)){
			if (isset($pluginvalue[$shop['sid']])){
				$shop['plugin'] = $pluginvalue[$shop['sid']];
			}
			$mshop[] = $shop;
		}
	}

	if (!submitcheck('paramsubmit')){

		loadcache('shops');
		$arrParam = array();
		$nParam = 0;
		$Param = 20;

		shownav('shop', 'shop_admin_param');
		showsubmenu(cplang('shop_admin_param') . (count($mshop) == 1 ? ' - ' . $mshop[0]['name'] . '(sid:' . $mshop[0]['sid'] . ')' : ''));
		showtips('shop_admin_param_tips');

		if ($nParam)
			showformheader("shops&operation=param&sid=$sid&nParam=$nParam");
		else
			showformheader("shops&operation=param&sid=$sid");

		showtableheader();
		$ParamOld = array();
		$query = DB::query("SELECT param
							FROM " . DB::table('shop_category') . " p
							WHERE sid = $sid");

		if (!DB::num_rows($query)){
			$arrID = array();
		}else{
			while ($shop = DB::fetch($query)){
				$ParamOld = $shop['param'];
				$ParamOld = unserialize($ParamOld);
			}
		}

		$nParam = getgpc('nParam');

		if ($nParam == 0)
			$nParam = intval(count($ParamOld));

		$styleselect = '<select name="paramnew" onchange="window.location.href=\'admin.php?action=shops&operation=param&sid=' . $sid . '&nParam=\'+this.value;">';
		$styleselect .= "<option value=\"\">$lang[shop_param_change]</option>";

		for ($n = 1; $n <= $Param; $n++){
			if ($n == $nParam)
				$styleselect .= '<option value="' . $n . '" selected="selected">' . $n . '</option>';
			else
				$styleselect .= '<option value="' . $n . '">' . $n . '</option>';
		}
		$styleselect .= '</select>';

		showsetting('shop_param_number', '', '', $styleselect);

		if ($nParam){
			for ($t = 0; $t < $nParam; $t++){
				$ParamValue = isset($ParamOld[$t]['value']) ? $ParamOld[$t]['value'] : getgpc('cat_' . $t);
				$ParamInfor = isset($ParamOld[$t]['infor']) ? $ParamOld[$t]['infor'] : getgpc('cat_infor_' . $t);
				$ParamExtra = (isset($ParamOld[$t]['extra']) && $ParamOld[$t]['extra'] == '1') || (getgpc('extra_' . $t) == '1') ? 'checked="checked"' : '';
				$ParamStick = (isset($ParamOld[$t]['stick']) && $ParamOld[$t]['stick'] == '1') || (getgpc('stick_' . $t) == '1') ? 'checked="checked"' : '';

				echo '<tr><td valign="top"><label>' . cplang("param_name") . ': </label> ';
				echo '<input type="text" name="cParam_' . $t . '" id="cParam_' . $t . '" class="cParam" value="' . $ParamOld[$t]['name'] . '" />';
				echo '<br /><label>' . cplang("param_infor") . ': </label> <textarea id="cat_infor_' . $t . '" cols="40" name="cat_infor_' . $t . '" rows="7">' . $ParamInfor . '</textarea>';
				echo '</td><td>';

				echo '<td valign="top"><label> ' . cplang('param_value') . ': </label> <input name="stick_' . $t . '" id="stick_' . $t . '" type="checkbox" value="1" ' . $ParamStick . '><label for="stick_' . $t . '">' . cplang('stick_information') . '</label>';

				echo '<p class="sub"><textarea cols="40" name="cat_' . $t . '" rows="7" id="cat_' . $t . '">' . $ParamValue . '</textarea></p><p class="sub"><input name="extra_' . $t . '" id="extra_' . $t . '" type="checkbox" value="1" ' . $ParamExtra . '><label for="extra_' . $t . '">' . cplang('cho_phep_nhap_them') . '</label></p>';
				echo '</td><td>';

				echo '<td valign="top"><label> ' . cplang('param_value_type') . ': </label> ';
				$ParamType = isset($ParamOld[$t]['type']) ? $ParamOld[$t]['type'] : getgpc('param_type_' . $t);
				if ($ParamType == 'select' || $ParamType == '')
					$selectedType = 'checked="checked"';
				else
					$selectedType = '';
				echo '<p class="sub"><input type="radio" value="select" name="param_type_' . $t . '" id="param_type_id_1_' . $t . '"' . $selectedType . ' /><label for="param_type_id_1_' . $t . '"> ' . cplang('param_value_type_1') . ' </label> </p>';

				if ($ParamType == 'checkbox')
					$selectedType = 'checked="checked"';
				else
					$selectedType = '';
				echo '<p class="sub"><input type="radio" value="checkbox" name="param_type_' . $t . '" id="param_type_id_2_' . $t . '"' . $selectedType . ' /><label for="param_type_id_2_' . $t . '"> ' . cplang('param_value_type_2') . ' </label> </p>';

				if ($ParamType == 'droplist')
					$selectedType = 'checked="checked"';
				else
					$selectedType = '';
				echo '<p class="sub"><input type="radio" value="droplist" name="param_type_' . $t . '" id="param_type_id_3_' . $t . '"' . $selectedType . ' /><label for="param_type_id_3_' . $t . '"> ' . cplang('param_value_type_3') . ' </label> </p>';

				if ($ParamType == 'List')
					$selectedType = 'checked="checked"';
				else
					$selectedType = '';
				echo '<p class="sub"><input type="radio" value="List" name="param_type_' . $t . '" id="param_type_id_4_' . $t . '"' . $selectedType . ' /><label for="param_type_id_4_' . $t . '"> ' . cplang('param_value_type_4') . ' </label> </p>';

				if ($ParamType == 'input')
					$selectedType = 'checked="checked"';
				else
					$selectedType = '';
				echo '<p class="sub"><input type="radio" value="input" name="param_type_' . $t . '" id="param_type_id_5_' . $t . '"' . $selectedType . ' /><label for="param_type_id_5_' . $t . '"> ' . cplang('param_value_type_5') . ' </label> </p>';

				if ($ParamType == 'textarea')
					$selectedType = 'checked="checked"';
				else
					$selectedType = '';
				echo '<p class="sub"><input type="radio" value="textarea" name="param_type_' . $t . '" id="param_type_id_6_' . $t . '"' . $selectedType . ' /><label for="param_type_id_6_' . $t . '"> ' . cplang('param_value_type_6') . ' </label> </p>';

				echo '</td>';

				echo '</tr>';
			}
		}

		showhiddenfields(array(
				'action'=>'shops',
				'operation'=>'param',
				'nparamnew'=>$t
		));

		showsubmit('paramsubmit');

		showtablefooter();
		showformfooter();
	}else{

		$nloop = $_G['gp_nparamnew'];

		$newParam = array();
		$newParamValue = array();

		for ($i = 0; $i < $nloop; $i++){
			if (trim(getgpc('cParam_' . $i)) != ''){
				$newParam[$i]['name'] = get_str_nohtml(trim(getgpc('cParam_' . $i)));
				$newParam[$i]['type'] = isset($_G['gp_param_type_' . $i]) ? $_G['gp_param_type_' . $i] : '';
				$newParam[$i]['value'] = isset($_G['gp_cat_' . $i]) ? get_str_nohtml($_G['gp_cat_' . $i]) : '';
				$newParam[$i]['extra'] = isset($_G['gp_extra_' . $i]) ? '1' : '0';
				$newParam[$i]['stick'] = isset($_G['gp_stick_' . $i]) ? '1' : '0';
				$newParam[$i]['infor'] = isset($_G['gp_cat_infor_' . $i]) ? get_str_nohtml($_G['gp_cat_infor_' . $i]) : ' ';
				$cat_param = 1;
			}
		}

		if (!empty($cat_param)){
			$newParam = serialize($newParam);
			$newParam = addslashes($newParam);
			DB::update('shop_category', array(
					'param'=>$newParam,
					'param_number'=>$nloop
			), "sid='$sid'");
			/*
			echo "<pre>";
			print_r($newParam);
			echo "</pre>";
			*/
			updatecache('shops');

			cpmsg('shop_update_succeed', 'action=shops', 'succeed');
		}else
			cpmsg('shop_update_error', 'action=shops', 'error');
	}
}

function showforum(&$shop, $type = '', $last = '', $toggle = false){
//var_dump($shop);
	global $_G;

	if ($last == ''){
		$return = '<tr class="hover">' . '<td class="td25"' . ($type == 'group' ? ' onclick="toggle_group(\'group_' . $shop['sid'] . '\', $(\'a_group_' . $shop['sid'] . '\'))"' : '') . '>' . ($type == 'group' ? '<a href="javascript:;" id="a_group_' . $shop['sid'] . '">' . ($toggle ? '[+]' : '[-]') . '</a>' : '') . '</td>
			<td class="td25"><input type="text" class="txt" name="order[' . $shop['sid'] . ']" value="' . $shop['displayorder'] . '" /></td><td>';
		if ($type == 'group'){
			$return .= '<div class="parentboard">';
			$_G['fg'] = !empty($_G['fg']) ? intval($_G['fg']) : 0;
			$_G['fg']++;
		}elseif ($type == ''){
			$return .= '<div class="board">';
		}elseif ($type == 'sub'){
			$return .= '<div id="cb_' . $shop['sid'] . '" class="childboard">';
		}

		$boardattr = '';
		if (!$shop['status'] || $shop['password'] || $shop['redirect']){
			$boardattr = '<div class="boardattr">';
			$boardattr .= $shop['status'] ? '' : cplang('forums_admin_hidden');
			$boardattr .= !$shop['password'] ? '' : ' ' . cplang('forums_admin_password');
			$boardattr .= !$shop['redirect'] ? '' : ' ' . cplang('forums_admin_url');
			$boardattr .= '</div>';
		}

		$cHot = '';
		if ($shop['hot'] == 1)
			$cHot = '<img src="/static/shop/images/icon_hot.gif" width="21" height="16" alt="Categories hot" />';

		$return .= '<input type="text" name="name[' . $shop['sid'] . ']" value="' . htmlspecialchars($shop['name']) . '" class="txt" />' . ($type == '' ? '<a href="###" onclick="addrowdirect = 1;addrow(this, 2, ' . $shop['sid'] . ')" class="addchildboard">' . cplang('shop_admin_add_shop') . '</a>' : '') . $cHot . '</div>' . $boardattr . '</td><td class="td25 lightfont">(' . ($type == 'group' ? 'gid:' : 'sid:') . $shop['sid'] . ')</td>' . '</td><td class="td23">' . showshop_moderators($shop) . '</td>
			<td width="160"><input class="checkbox" value="' . $shop['sid'] . '" type="checkbox"' . ($type != 'group' ? ' chkvalue="g' . $_G['fg'] . '" onclick="multiupdate(this, ' . $shop['sid'] . ')"' : ' name="gc' . $_G['fg'] . '" onclick="checkAll(\'value\', this.form, \'g' . $_G['fg'] . '\', \'gc' . $_G['fg'] . '\', 1)"') . ' />' . ($type != 'group' ? '<a href="' . ADMINSCRIPT . '?action=shops&operation=param&sid=' . $shop['sid'] . '" title="' . cplang('shop_param_comment') . '" class="act">' . cplang('param') . '</a>' : '') . '
			<a href="' . ADMINSCRIPT . '?action=shops&operation=edit&sid=' . $shop['sid'] . '" title="' . cplang('forums_edit_comment') . '" class="act">' . cplang('edit') . '</a>'.
			'<a href="' . ADMINSCRIPT . '?action=shops&operation=delete&sid=' . $shop['sid'] . '" title="' . cplang('forums_delete_comment') . '" class="act">' . cplang('delete') . '</a></td></tr>';
		if ($type == 'group')
			$return .= '<tbody id="group_' . $shop['sid'] . '"' . ($toggle ? ' style="display:none;"' : '') . '>';
	}else{
		if ($last == 'lastboard'){
			$return = '</tbody><tr><td></td><td colspan="4"><div class="lastboard"><a href="###" onclick="addrow(this, 1, ' . $shop['sid'] . ')" class="addtr">' . cplang('shop_admin_add_shop') . '</a></div></td><td>&nbsp;</td></tr>';
		}elseif ($last == 'lastchildboard' && $type){
			$return = '<script type="text/JavaScript">$(\'cb_' . $type . '\').className = \'lastchildboard\';</script>';
		}elseif ($last == 'last'){
			$return = '</tbody><tr><td></td><td colspan="4"><div><a href="###" onclick="addrow(this, 0)" class="addtr">' . cplang('forums_admin_add_category') . '</a></div></td>' . '<td class="bold"><a href="javascript:;" onclick="if(getmultiids()) location.href=\'' . ADMINSCRIPT . '?action=shops&operation=edit&multi=\' + getmultiids();return false;">' . cplang('multiedit') . '</a></td>' . '</tr>';
		}
	}

	echo $return = isset($return) ? $return : '';

	return $shop['sid'];
}

function showshop_moderators($shop){
	global $_G;
	if ($shop['moderators']){
		$moderators = explode("\t", $shop['moderators']);
		$count = count($moderators);
		$max = $count > 2 ? 2 : $count;
		$mods = array();
		for ($i = 0; $i < $max; $i++){
			$mods[] = $shop['inheritedmod'] ? '<b>' . $moderators[$i] . '</b>' : $moderators[$i];
		}
		$r = implode(', ', $mods);
		if ($count > 2){
			$r = '<span onmouseover="showMenu({\'ctrlid\':this.id})" id="mods_' . $shop['sid'] . '">' . $r . '</span>';
			$mods = array();
			foreach ($moderators as $moderator){
				$mods[] = $shop['inheritedmod'] ? '<b>' . $moderator . '</b>' : $moderator;
			}
			$r = '<a href="' . ADMINSCRIPT . '?action=shops&operation=moderators&sid=' . $shop['sid'] . '" title="' . cplang('forums_moderators_comment') . '">' . $r . ' &raquo;</a>';
			$r .= '<div class="dropmenu1" id="mods_' . $shop['sid'] . '_menu" style="display: none">' . implode('<br />', $mods) . '</div>';
		}else{
			$r = '<a href="' . ADMINSCRIPT . '?action=shops&operation=moderators&sid=' . $shop['sid'] . '" title="' . cplang('forums_moderators_comment') . '">' . $r . ' &raquo;</a>';
		}

	}else{
		$r = '<a href="' . ADMINSCRIPT . '?action=shops&operation=moderators&sid=' . $shop['sid'] . '" title="' . cplang('forums_moderators_comment') . '">' . cplang('forums_admin_no_moderator') . '</a>';
	}
	return $r;
}

function fetch_table_struct($tablename, $result = 'FIELD'){
	$datas = array();
	$query = DB::query("DESCRIBE " . DB::table($tablename));
	while ($data = DB::fetch($query)){
		$datas[$data['Field']] = $result == 'FIELD' ? $data['Field'] : $data;
	}
	return $datas;
}

function getthreadclasses_html($sid){
	$threadtypes = DB::result_first("SELECT threadtypes FROM " . DB::table('shop_shopfield') . " WHERE sid='$sid'");
	$threadtypes = unserialize($threadtypes);

	$query = DB::query("SELECT * FROM " . DB::table('shop_threadclass') . " WHERE sid='$sid' ORDER BY displayorder");
	while ($type = DB::fetch($query)){
		$enablechecked = $moderatorschecked = '';
		$typeselected = array();
		if (isset($threadtypes['types'][$type['typeid']])){
			$enablechecked = ' checked="checked"';
		}
		if ($type['moderators']){
			$moderatorschecked = ' checked="checked"';
		}
		$typeselect .= showtablerow('', array(
				'class="td25"'
		), array(
				"<input type=\"checkbox\" class=\"checkbox\" name=\"threadtypesnew[options][delete][]\" value=\"{$type['typeid']}\" />",
				"<input type=\"text\" size=\"2\" name=\"threadtypesnew[options][displayorder][{$type['typeid']}]\" value=\"{$type['displayorder']}\" />",
				"<input type=\"text\" name=\"threadtypesnew[options][name][{$type['typeid']}]\" value=\"" . (str_replace(array(
						"'",
						"\""
				), array(), $type['name'])) . "\" />",
				"<input type=\"text\" name=\"threadtypesnew[options][icon][{$type['typeid']}]\" value=\"{$type['icon']}\" />",
				'<input type="checkbox" name="threadtypesnew[options][enable][' . $type['typeid'] . ']" value="1" class="checkbox"' . $enablechecked . ' />',
				"<input type=\"checkbox\" class=\"checkbox\" name=\"threadtypesnew[options][moderators][{$type['typeid']}]\" value=\"1\"{$moderatorschecked} />"
		), TRUE);
	}
	return $typeselect;
}

function get_shop_by_sid($sid, $field = '', $table = 'category'){
	static $shoplist = array(
			'shop'=>array(),
			'shopfield'=>array()
	);
	$table = $table != 'category' ? 'shopfield' : 'category';
	$return = array();
	if (!array_key_exists($sid, $shoplist[$table])){
		$shoplist[$table][$sid] = DB::fetch_first("SELECT * FROM " . DB::table('shop_' . $table) . " WHERE sid='$sid'");
		if (!is_array($shoplist[$table][$sid])){
			$shoplist[$table][$sid] = array();
		}
	}

	if (!empty($field)){
		$return = isset($shoplist[$table][$sid][$field]) ? $shoplist[$table][$sid][$field] : null;
	}else{
		$return = $shoplist[$table][$sid];
	}
	return $return;
}

function get_subsids($sid){
	global $subsids, $_G;
	$subsids[] = $sid;
	foreach ($_G['cache']['shops'] as $key=>$value){
		if ($value['sup'] == $sid){
			get_subsids($value['sid']);
		}
	}
}

function copy_threadclasses($threadtypes, $sid){
	global $_G;
	if ($threadtypes){
		$threadtypes = unserialize($threadtypes);
		$i = 0;
		$data = array();
		foreach ($threadtypes['types'] as $key=>$val){
			$data = array(
					'sid'=>$sid,
					'name'=>addslashes($val),
					'displayorder'=>$i++,
					'icon'=>addslashes($threadtypes['icons'][$key]),
					'moderators'=>$threadtypes['moderators'][$key]
			);
			$newtypeid = DB::insert('shop_threadclass', $data, 1);
			$newtypes[$newtypeid] = $val;
			$newicons[$newtypeid] = $threadtypes['icons'][$key];
			$newmoderators[$newtypeid] = $threadtypes['moderators'][$key];
		}
		$threadtypes['types'] = $newtypes;
		$threadtypes['icons'] = $newicons;
		$threadtypes['moderators'] = $newmoderators;
		return serialize($threadtypes);
	}
	return '';
}
function get_str_nohtml($string){
	if (is_array($string)){
		foreach ($string as $key=>$val){
			$string[$key] = get_str_nohtml($val);
		}
	}else{
		$string = trim(str_replace(array(
				"'",
				'"',
				'<',
				'>',
				'\t'
		), array(
				'&rsquo;',
				'&quot;',
				'&lt;',
				'&gt;',
				' '
		), $string));
	}
	return pdstripcslashes($string);
}
function pdstripcslashes($string){
	if (is_array($string)){
		foreach ($string as $key=>$val){
			$string[$key] = pdstripcslashes($val);
		}
	}else{
		$string = stripcslashes($string);
	}
	return $string;
}
?>